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.user.TbSysUser;
import org.xyzh.common.utils.NonUtils;
import org.xyzh.api.system.user.UserService;

import java.util.List;

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

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

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

    @Autowired
    private UserService 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 TbSysUser findUser(LoginParam loginParam) {
        TbSysUser filter = new TbSysUser();
        if (NonUtils.isNotEmpty(loginParam.getUsername())) {
            filter.setUsername(loginParam.getUsername());
        }
        if (NonUtils.isNotEmpty(loginParam.getEmail())) {
            filter.setEmail(loginParam.getEmail());
        }
        if (NonUtils.isNotEmpty(loginParam.getPhone())) {
            filter.setPhone(loginParam.getPhone());
        }
        List<TbSysUser> users = userService.getUserByFilter(filter).getDataList();
        if(users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public boolean verifyCredential(String inputCredential, String storedCredential) {
        logger.info(passwordEncoder.encode(inputCredential));
        return passwordEncoder.matches(inputCredential, storedCredential);
    }
}