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    UsernameLoginStrategy.java文件描述 用户名登录策略
 * @filename    UsernameLoginStrategy.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Component
public class UsernameLoginStrategy implements LoginStrategy {

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

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