package org.springblade.system.config;

import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 密码弱密码校验工具类（仅校验是否为常见弱密码）
 */
@Component
public class WeakPasswordChecker {

    private static final List<String> WEAK_PASSWORDS = Arrays.asList(
            "123456",
            "123456789",
            "password",
            "12345678",
            "12345",
            "1234567",
            "1234567890",
            "qwerty",
            "abc123",
            "111111",
            "admin",
            "letmein",
            "monkey",
            "welcome",
            "123123",
            "login",
            "princess",
            "dragon",
            "sunshine",
            "iloveyou",
            "starwars",
            "football",
            "123qwe",
            "root",
            "password1",
            "admin123",
            "111",
            "888",
            "123",
            "234",
            "345",
            "456",
            "567",
            "678",
            "789",
            "1234",
            "2345",
            "3456",
            "4567",
            "5678",
            "6789",
            "abc",
            "abcd",
            "abcde",
            "abcdef",
            "abcdefg",
            "qwe",
            "qwer",
            "qwert",
            "asdf",
            "asdfg",
            "asdfgh",
            "user",
            "test",
            "pass"
    );

    // 使用 Map 存储：小写密码 -> 原始密码（用于快速查找 + 返回原始格式）
    private static final Map<String, String> WEAK_PASSWORD_MAP = WEAK_PASSWORDS.stream()
            .collect(Collectors.toMap(
                    String::toLowerCase,
                    pwd -> pwd,
                    (existing, replacement) -> existing
            ));

    public static String checkWeakPasswordAndGetMatch(String password) {
        if (password == null || password.length() < 8 || password.length() > 20) {
            return "密码长度必须为 8-20 位";
        }

        String lowerPwd = password.toLowerCase();

        if (WEAK_PASSWORD_MAP.containsKey(lowerPwd)) {
            String originalWeak = WEAK_PASSWORD_MAP.get(lowerPwd);
            return "密码过于简单，避免使用如 '" + originalWeak + "' 类密码";
        }

        // 正则：必须包含 小写、大写、数字、特殊字符
        if (!password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\w\\s]).+$")) {
            return "密码必须包含：小写字母、大写字母、数字、特殊字符";
        }
        return null;
    }
}
