package com.example.sjkbf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sjkbf.entity.AuthUser;
import com.example.sjkbf.entity.User;
import com.example.sjkbf.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.Service;

/**
 *用户认证类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    // 构造器注入（推荐）
    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        try {

            // 1. 查询数据库
            user= userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        }catch (Exception e){
            e.printStackTrace();
        }

        // 2. 用户不存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 3. 转换为 Spring Security 的 UserDetails 对象
        return new AuthUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                AuthorityUtils.createAuthorityList("ROLE_ALL") // 假设 roles 字段存储如 "ROLE_ADMIN,ROLE_USER"
        );
    }
}