package org.xyzh.auth.strategy.impl;

import org.springframework.stereotype.Component;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.xyzh.auth.strategy.LoginStrategy;
import org.xyzh.common.core.domain.LoginParam;
import org.xyzh.common.dto.sys.TbSysUserDTO;
import org.xyzh.common.utils.NonUtils;
import org.xyzh.common.utils.crypto.AesEncryptUtil;
import org.xyzh.common.utils.validation.method.EmailValidateMethod;
import org.xyzh.common.utils.validation.method.PhoneValidateMethod;
import org.xyzh.api.system.service.SysUserService;
import org.xyzh.api.system.vo.SysUserVO;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description    PasswordLoginStrategy.java文件描述 密码登录策略
 * @filename    PasswordLoginStrategy.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-05
 */
@Component
public class PasswordLoginStrategy implements LoginStrategy {

    private static final Logger logger = LoggerFactory.getLogger(PasswordLoginStrategy.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public String getLoginType() {
        return "password";
    }

    @Override
    public boolean validate(LoginParam loginParam) {
        if (NonUtils.isEmpty(loginParam.getPassword())) {
            return false;
        }

        if (NonUtils.isEmpty(loginParam.getUsername()) && NonUtils.isEmpty(loginParam.getEmail()) && NonUtils.isEmpty(loginParam.getPhone())) {
            return false;
        }

        return true;
    }

    @Override
    public SysUserVO findUser(LoginParam loginParam) {
        SysUserVO filter = new SysUserVO();
        EmailValidateMethod emailValidateMethod = new EmailValidateMethod();
        PhoneValidateMethod phoneValidateMethod = new PhoneValidateMethod();
        if(emailValidateMethod.validate(loginParam.getUsername())){
            filter.setEmail(loginParam.getUsername());
        }else if (phoneValidateMethod.validate(loginParam.getUsername())){
            filter.setPhone(loginParam.getUsername());
        }else{
            filter.setUsername(loginParam.getUsername());
        }
        // 【优化】删除无用的密码编码，SQL查询不使用password字段
        // 密码验证在 verifyCredential() 方法中进行
        SysUserVO user = userService.getLoginUser(filter).getData();
        if(user == null) {
            return null;
        }
        return user;
    }

    @Override
    public boolean verifyCredential(String inputCredential, String storedCredential) {
        // 使用BCrypt的matches方法验证密码（内部会自动处理salt）
        logger.info(passwordEncoder.encode(inputCredential));
        return passwordEncoder.matches(inputCredential, storedCredential);
    }
}