package de.szut.casino.security.service;

import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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.ArrayList;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
        Optional<UserEntity> user = userRepository.findByUsername(usernameOrEmail);
        
        if (user.isEmpty()) {
            user = userRepository.findByEmail(usernameOrEmail);
        }
        
        UserEntity userEntity = user.orElseThrow(() -> 
                new UsernameNotFoundException("User not found with username or email: " + usernameOrEmail));
        
        return new org.springframework.security.core.userdetails.User(
                userEntity.getUsername(), 
                userEntity.getPassword(), 
                new ArrayList<>());
    }
}
