package org.ta.authserver2.config;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.ta.authserver2.service.UserService;
import org.ta.commoncore.model.User;

@Slf4j
public class UserDetailsManager implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("UserDetailsManager loadUserByUsername username={}", username);
        User user = userService.getByUsername(username);

        if (user == null) {
            log.info("UserDetailsManager loadUserByUsername user is null");
            //用户不存在，抛出异常
            throw new UsernameNotFoundException(username);
        } else {
            log.info("UserDetailsManager loadUserByUsername user is find!");
            return org.springframework.security.core.userdetails.User.withUsername(user.getUsername())
                    .password(user.getPassword())
                    .roles("admin", "normal")
                    .authorities("delete", "update")
                    .build();

            //由于现在还没有权限信息，所以我们构造一个空的权限信息
//            Collection<GrantedAuthority> authorities = new ArrayList<>();
//            return new org.springframework.security.core.userdetails.User(
//                    user.getUsername(),  //
//                    user.getPassword(),
//                    user.getEnabled(),
//                    true,  //用户账户是否没过期
//                    true, //用户凭证是否没过期
//                    true, //用户是否未被锁定
//                    authorities //用户权限信息
//            );
        }
    }
}
