package top.imwork.window.silos.security.details;

import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import top.imwork.commons.core.exception.BusinessException;
import top.imwork.window.silos.dao.SysRoleDao;
import top.imwork.window.silos.dao.SysUserDao;
import top.imwork.window.silos.entity.upms.SysRole;
import top.imwork.window.silos.entity.upms.SysUser;
import top.imwork.window.silos.exception.AccountFoundMoreException;

import java.util.List;

/**
 * Copyright (C), 2015-2025
 * FileName: SecurityUserDetailsService
 * Author<作者姓名>:   stars
 * CreateTime<创建时间>:   2025/12/10 13:19
 * UpdateTime<修改时间>:   2025/12/10 13:19
 * Description〈功能简述〉: SecurityUserDetailsService用于认证用户名、密码、授权等
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
@Component
public class SecurityUserDetailsService implements UserDetailsService {
    @Resource
    private SysUserDao userDao;
    @Resource
    private SysRoleDao roleDao;
    /**
     * 重写UserDetailsService接口里面的抽象方法
     * 根据用户名 返回一个UserDetails的实现类的实例
     * 查到User后将其封装为UserDetails的实现类的实例供程序调用
     * 用该User和它对应的Role实体们构造UserDetails的实现类
     * <p>
     * 账号密码登录方式
     *
     * @param username 用户登录名称
     * @return UserDetails 用户详情
     * @throws UsernameNotFoundException 用户信息不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SysUser> users = userDao.getUserByAccount(username);

        if (ObjectUtils.isEmpty(users)) {
            throw new UsernameNotFoundException("账户信息不存在!");
        } else if (users.size() > 1) {
            throw new AccountFoundMoreException("账户信息异常,查询出多用户!");
        } else {
            SysUser user = users.getFirst();
            List<SysRole> roles = roleDao.getRolesByUserId(user.getId());
            if (ObjectUtils.isEmpty(roles)) {
                throw new BusinessException("用户角色未分配,请联系管理员!");
            } else {
                return new SecurityUserDetails(user, roles);
            }
        }
    }
}