package com.imprimelibros.erp.users;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Adaptador de la entidad User a Spring Security.
 */
public class UserDetailsImpl implements UserDetails {

    private final User user;

    public UserDetailsImpl(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // Si tu User tiene un Set<Role>:
        Set<String> roles = user.getRoles().stream()
                .map(r -> r.getName()) // ejemplo: "ADMIN", "USER"
                .collect(Collectors.toSet());

        return roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toSet());
    }

    @Override
    public String getPassword() {
        return user.getPassword(); // debe estar encriptado (BCrypt)
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    public String getFullname() {
        
        return user.getFullName(); 
    }

    // 👇 si en la vista usas principal.role, añade este también
    public String getRole() {
        return user.getRoles().stream()
                .map(r -> r.getName()) // "ADMIN", "USER", ...
                .findFirst()
                .orElse("-");
    }

    /** (Opcional) Todos los roles “limpios” por si quieres listarlos. */
    public java.util.Set<String> getRoleNames() {
        return user.getRoles().stream()
                .map(r -> r.getName())
                .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true; // puedes añadir lógica si quieres
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true; // igual que arriba
    }

    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }

    public User getUser() {
        return user;
    }
}
