package studycave.studycaverestservice.model.user;

import org.springframework.security.core.userdetails.User;
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.stereotype.Service;

import static java.util.Collections.emptyList;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private UserRepository applicationUserRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserDetailsServiceImpl(UserRepository applicationUserRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.applicationUserRepository = applicationUserRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        studycave.studycaverestservice.model.user.User applicationUser = applicationUserRepository.findByUsername(username).orElse(null);
        if (applicationUser == null) {
            throw new UsernameNotFoundException(username);
        }
        if (applicationUser.getUsosUser() != null)
            applicationUser.setPassword(applicationUser.getUsosUser().getPassword());

        return new User(applicationUser.getUsername(), applicationUser.getPassword(), emptyList());
    }
}
