package com.huimv.employment.common.util;

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

import java.util.regex.Pattern;

/**
 * 登录密码强度校验。
 */
public final class PasswordPolicyUtils {

    private static final Pattern HAS_LETTER = Pattern.compile("[A-Za-z]");
    private static final Pattern HAS_DIGIT = Pattern.compile("\\d");

    private PasswordPolicyUtils() {
    }

    public static void validate(String rawPassword, String mobilePlain) {
        if (rawPassword == null || rawPassword.isEmpty()) {
            throw new BizException(ErrorCode.BAD_REQUEST, "密码不能为空");
        }
        if (rawPassword.length() < 8 || rawPassword.length() > 64) {
            throw new BizException(ErrorCode.PASSWORD_FORMAT_INVALID, "密码长度为 8-64 位");
        }
        if (!HAS_LETTER.matcher(rawPassword).find() || !HAS_DIGIT.matcher(rawPassword).find()) {
            throw new BizException(ErrorCode.PASSWORD_FORMAT_INVALID, "密码须同时包含字母和数字");
        }
        if (mobilePlain != null && !mobilePlain.isEmpty() && rawPassword.equals(mobilePlain)) {
            throw new BizException(ErrorCode.PASSWORD_FORMAT_INVALID, "密码不能与手机号相同");
        }
    }

    public static void validateConfirm(String rawPassword, String confirmPassword) {
        if (confirmPassword == null || confirmPassword.isEmpty()) {
            throw new BizException(ErrorCode.BAD_REQUEST, "确认密码不能为空");
        }
        if (!rawPassword.equals(confirmPassword)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "两次输入的密码不一致");
        }
    }
}
