package de.hft.geotime.security;

import de.hft.geotime.entities.TimetrackUser;
import de.hft.geotime.repositories.TimetrackUserRepository;
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.stereotype.Service;

import java.util.Collections;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final TimetrackUserRepository userRepository;

    public UserDetailsServiceImpl(TimetrackUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TimetrackUser timetrackUser = userRepository.findFirstByUsername(username);
        if (timetrackUser == null) {
            throw new UsernameNotFoundException(username);
        }
        System.out.println("Loaded user " + timetrackUser.getFirstname() + " " + timetrackUser.getLastname());
        return new User(timetrackUser.getUsername(), timetrackUser.getPassword(), Collections.emptyList());
    }
}
