package com.writeoff.security;

import com.writeoff.common.exception.BusinessException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 密码策略校验服务。
 * 规则：
 * - 最少8位
 * - 必须包含大写字母
 * - 必须包含小写字母
 * - 必须包含数字
 * - 必须包含特殊字符
 */
@Service
public class PasswordPolicyService {

    private static final int MIN_LENGTH = 8;
    private static final Pattern UPPER = Pattern.compile("[A-Z]");
    private static final Pattern LOWER = Pattern.compile("[a-z]");
    private static final Pattern DIGIT = Pattern.compile("[0-9]");
    private static final Pattern SPECIAL = Pattern.compile("[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?`~]");

    /**
     * 校验密码强度，不满足则抛 BusinessException。
     */
    public void validate(String password) {
        List<String> violations = check(password);
        if (!violations.isEmpty()) {
            throw new BusinessException(10001, "密码强度不足：" + String.join("；", violations));
        }
    }

    /**
     * 检查密码强度，返回不满足的规则列表（空列表表示通过）。
     */
    public List<String> check(String password) {
        List<String> violations = new ArrayList<>();
        if (password == null || password.length() < MIN_LENGTH) {
            violations.add("密码长度至少" + MIN_LENGTH + "位");
        }
        if (password == null || !UPPER.matcher(password).find()) {
            violations.add("需包含大写字母");
        }
        if (password == null || !LOWER.matcher(password).find()) {
            violations.add("需包含小写字母");
        }
        if (password == null || !DIGIT.matcher(password).find()) {
            violations.add("需包含数字");
        }
        if (password == null || !SPECIAL.matcher(password).find()) {
            violations.add("需包含特殊字符");
        }
        return violations;
    }
}
