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.api.system.user.UserService;

import java.util.List;

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

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Override
    public boolean validate(LoginParam loginParam) {
        return loginParam.getPhone() != null && !loginParam.getPhone().trim().isEmpty()
                && (loginParam.getPassword() != null || loginParam.getCaptcha() != null);
    }

    @Override
    public TbSysUser findUser(LoginParam loginParam) {
        TbSysUser filter = new TbSysUser();
        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) {
        // 手机号登录可能使用验证码，如果有验证码则跳过密码验证
        if (inputCredential == null) {
            return true; // 假设验证码已经在其他地方验证过了
        }
        return passwordEncoder.matches(inputCredential, storedCredential);
    }
}