package com.CUST.brain.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * 密码编码器
 */
@Component
public class PasswordEncoder extends BCryptPasswordEncoder {
    private static final Logger log = LoggerFactory.getLogger(PasswordEncoder.class);

    public PasswordEncoder() {
        super(10); // 使用强度为10的BCrypt加密
    }

    @PostConstruct
    public void testPasswordEncoder() {
        // 测试1：使用当前实例
        String rawPassword = "admin123";
        String encodedPassword = encode(rawPassword);
        log.info("测试1 - 当前实例 - 原始密码: {}, 加密后: {}", rawPassword, encodedPassword);
        boolean matches = matches(rawPassword, encodedPassword);
        log.info("测试1 - 当前实例 - 匹配结果: {}", matches);
        
        // 测试2：使用数据库中的密码
        String dbPassword = "$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBOsl7iKTVKIUi";
        boolean dbMatches = matches(rawPassword, dbPassword);
        log.info("测试2 - 当前实例 - 数据库密码匹配结果: {}", dbMatches);
        
        // 测试3：使用新的 BCryptPasswordEncoder 实例
        BCryptPasswordEncoder newEncoder = new BCryptPasswordEncoder(10);
        String newEncoded = newEncoder.encode(rawPassword);
        log.info("测试3 - 新实例 - 原始密码: {}, 加密后: {}", rawPassword, newEncoded);
        boolean newMatches = newEncoder.matches(rawPassword, newEncoded);
        log.info("测试3 - 新实例 - 匹配结果: {}", newMatches);
        
        // 测试4：使用新实例匹配数据库密码
        boolean newDbMatches = newEncoder.matches(rawPassword, dbPassword);
        log.info("测试4 - 新实例 - 数据库密码匹配结果: {}", newDbMatches);
    }

    @Override
    public String encode(CharSequence rawPassword) {
        String encoded = super.encode(rawPassword);
        log.debug("密码加密 - 原始密码: {}, 加密后: {}", rawPassword, encoded);
        return encoded;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        boolean matches = super.matches(rawPassword, encodedPassword);
        log.debug("密码匹配 - 原始密码: {}, 加密密码: {}, 匹配结果: {}", rawPassword, encodedPassword, matches);
        return matches;
    }
} 