package com.example.csbananasite.service;

import com.example.csbananasite.model.Role;
import com.example.csbananasite.model.UserCS;
import com.example.csbananasite.repo.UserCSRepo;
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 org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserCSRepo userCSRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserCS user = userCSRepo.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Пользователь не найден");
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getAuthorities()
        );
    }

    public void registerNewUser(String username, String password) {
        UserCS newUser = new UserCS(username, password, Set.of(Role.ROLE_USER));
        userCSRepo.save(newUser);
    }

    public void registerAdmin(String username, String password) {
        UserCS adminUser = new UserCS(username, password, Set.of(Role.ROLE_ADMIN));
        userCSRepo.save(adminUser);
    }
}