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.api.system.service.SysUserService;
import org.xyzh.api.system.vo.SysUserVO;

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

    @Autowired
    private SysUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

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

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

    @Override
    public SysUserVO findUser(LoginParam loginParam) {
        SysUserVO filter = new SysUserVO();
        filter.setUsername(loginParam.getUsername());
        SysUserVO user = userService.getLoginUser(filter).getData();
        if(user == null) {
            return null;
        }
        return user;
    }

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