package org.ta.pddserver.config.security;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.ta.pddserver.entity.UserEntity;
import org.ta.pddserver.service.impl.UserImpl;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserImpl userService;
    @Resource
    PasswordEncoder passwordEncoder;



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

        log.info("UserDetailsManager loadUserByUsername username={}", username);
        UserEntity userEntity = userService.getInfoByAccount(username);

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