package com.ga.common.util;

/**
 * 개인정보 마스킹 유틸.
 * - NAME : 홍길동 → 홍*동
 * - PHONE: 010-1234-5678 → 010-****-5678
 * - RRN  : 880101-1234567 → 880101-*******
 * - ACCT : 110-123-456789 → 110-***-******
 * - EMAIL: aaa@bbb.com → a**@bbb.com
 */
public final class MaskUtil {

    private MaskUtil() {}

    public enum MaskType { NAME, PHONE, RRN, ACCOUNT, EMAIL }

    public static String mask(String value, MaskType type) {
        if (value == null || value.isBlank()) return value;
        return switch (type) {
            case NAME    -> maskName(value);
            case PHONE   -> maskPhone(value);
            case RRN     -> maskRrn(value);
            case ACCOUNT -> maskAccount(value);
            case EMAIL   -> maskEmail(value);
        };
    }

    public static String maskName(String name) {
        int len = name.length();
        if (len <= 1) return name;
        if (len == 2) return name.charAt(0) + "*";
        return name.charAt(0) + "*".repeat(len - 2) + name.charAt(len - 1);
    }

    public static String maskPhone(String phone) {
        String digits = phone.replaceAll("[^0-9]", "");
        if (digits.length() == 11) {
            return digits.substring(0, 3) + "-****-" + digits.substring(7);
        }
        if (digits.length() == 10) {
            return digits.substring(0, 3) + "-***-" + digits.substring(6);
        }
        return phone;
    }

    public static String maskRrn(String rrn) {
        String s = rrn.replaceAll("[^0-9]", "");
        if (s.length() != 13) return rrn;
        return s.substring(0, 6) + "-*******";
    }

    public static String maskAccount(String account) {
        if (account == null) return null;
        String[] parts = account.split("-");
        if (parts.length >= 2) {
            StringBuilder sb = new StringBuilder(parts[0]);
            for (int i = 1; i < parts.length; i++) {
                sb.append('-').append("*".repeat(parts[i].length()));
            }
            return sb.toString();
        }
        if (account.length() <= 4) return account;
        return account.substring(0, 4) + "*".repeat(account.length() - 4);
    }

    public static String maskEmail(String email) {
        int at = email.indexOf('@');
        if (at <= 1) return email;
        String id = email.substring(0, at);
        String domain = email.substring(at);
        return id.charAt(0) + "*".repeat(id.length() - 1) + domain;
    }
}
