package com.printhub.printhub.service.configuration;

import com.printhub.printhub.entity.configuration.User;
import com.printhub.printhub.repository.configuration.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public void register(String username, String password, String roleName) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEnabled(true);
        // NOTA: aquí deberías asociar roles desde RoleRepository, lo dejamos en blanco
        // por ahora
        userRepository.save(user);
    }

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Usuario no encontrado"));

        List<GrantedAuthority> authorities = user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(permission -> new SimpleGrantedAuthority(
                        permission.getModule().getName().toUpperCase() + ":" + permission.getAction().toUpperCase()))
                .distinct()
                .collect(Collectors.toList());

        // DEBUG: mostrar en consola los permisos asignados
        /*System.out.println("→ Roles del usuario:");
        user.getRoles().forEach(role -> {
            System.out.println("  Role: " + role.getName());
            role.getPermissions().forEach(
                    perm -> System.out.println("    Perm: " + perm.getModule().getName() + ":" + perm.getAction()));
        });*/

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.isEnabled(),
                true, true, true,
                authorities);
    }

}
