package com.dne.ems.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 密码验证器，用于验证密码是否符合系统安全要求
 * 
 * <p>实现了Jakarta Validation的ConstraintValidator接口，
 * 用于验证带有@ValidPassword注解的字段。密码必须满足以下条件：</p>
 * <ul>
 *   <li>至少8个字符长</li>
 *   <li>至少包含一个数字</li>
 *   <li>至少包含一个小写字母</li>
 *   <li>至少包含一个大写字母</li>
 *   <li>至少包含一个特殊字符</li>
 *   <li>不允许包含空格</li>
 * </ul>
 *
 * @see ValidPassword
 */
public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {

    // (?=.*[0-9]) a digit must occur at least once
    // (?=.*[a-z]) a lower case letter must occur at least once
    // (?=.*[A-Z]) an upper case letter must occur at least once
    // (?=.*[!@#$%^&*()]) a special character must occur at least once
    // (?=\\S+$) no whitespace allowed in the entire string
    // .{8,} at least 8 characters
    private static final String PASSWORD_PATTERN =
            "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]).{8,}$";

    private static final Pattern PATTERN = Pattern.compile(PASSWORD_PATTERN);

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        if (password == null) {
            return false;
        }
        return PATTERN.matcher(password).matches();
    }
}