package com.example.chiptuningweb.service;

import com.example.chiptuningweb.model.UserChip;
import com.example.chiptuningweb.model.Role;
import com.example.chiptuningweb.repo.UserChipRepo;
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 UserChipRepo userChipRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserChip user = userChipRepo.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) {
        UserChip newUser = new UserChip(username, password, Set.of(Role.ROLE_USER));
        userChipRepo.save(newUser);
    }

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