package com.app.quiz.service;

import com.app.quiz.model.User;
import org.springframework.security.authentication.BadCredentialsException;
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.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class QuizUserDetailsService implements UserDetailsService {

    private final List<User> users = new ArrayList<>();
    private final PasswordEncoder passwordEncoder;

    public QuizUserDetailsService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = users.stream().filter(u -> u.getUsername().equals(username)).findFirst();
        if (user.isEmpty()) {
            throw new UsernameNotFoundException("User %s not found".formatted(username));
        }
        return org.springframework.security.core.userdetails.User
                .withUsername(user.get().getUsername())
                .password(user.get().getPassword())
                .roles(user.get().getRole())
                .build();
    }

    public void registerUser(String username, String password, String email, String role) {
        if (users.stream().anyMatch(u -> u.getUsername().equals(username))) {
            throw new BadCredentialsException("Username already exists");
        }
        users.add(new User(username, email, passwordEncoder.encode(password), role));
    }

}