package com.huimv.employment.common.util;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 登录用户名格式校验与规范化。
 */
public final class UsernameUtils {

    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]{5,19}$");

    private static final Set<String> RESERVED = new HashSet<>(Arrays.asList(
            "admin", "system", "root", "test", "guest", "null", "undefined"));

    private UsernameUtils() {
    }

    public static String normalize(String username) {
        if (username == null || username.trim().isEmpty()) {
            throw new BizException(ErrorCode.BAD_REQUEST, "用户名不能为空");
        }
        return username.trim().toLowerCase();
    }

    public static void validate(String username) {
        String normalized = normalize(username);
        if (!USERNAME_PATTERN.matcher(normalized).matches()) {
            throw new BizException(ErrorCode.PASSWORD_FORMAT_INVALID, "用户名为 6-20 位，字母开头，仅含字母、数字、下划线");
        }
        if (RESERVED.contains(normalized)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "用户名不可用");
        }
    }

    public static String mask(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        String n = username.trim();
        if (n.length() <= 2) {
            return n.charAt(0) + "*";
        }
        return n.substring(0, 2) + "***" + n.substring(n.length() - 1);
    }
}
