package cn.bunny.service.security;

import cn.bunny.dto.user.LoginDto;
import cn.bunny.entity.system.admin.AdminRole;
import cn.bunny.entity.system.user.User;
import cn.bunny.security.custom.CustomUser;
import cn.bunny.service.mapper.AdminRoleMapper;
import cn.bunny.service.mapper.UserMapper;
import cn.bunny.service.service.UserService;
import cn.bunny.vo.system.login.LoginVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

@Configuration
public class CustomUserDetailsService implements cn.bunny.security.service.CustomUserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据邮箱查询用户名
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getEmail, username));
        List<AdminRole> sysRoleList = adminRoleMapper.selectList(null);
        // 都为空抛出异常，用户不存在
        if (user == null) {
            throw new UsernameNotFoundException("");
        }

        // 查询所有的角色
        List<String> roleAuthoritieList = sysRoleList.stream().map(AdminRole::getRoleCode).toList();
        return new CustomUser(user, AuthorityUtils.createAuthorityList(roleAuthoritieList));
    }

    /**
     * 前台用户登录接口
     *
     * @param loginDto 登录参数
     * @return 登录后结果返回
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        return userService.login(loginDto);
    }
}