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.LinkedHashSet;

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

    private final User user;
    private final java.util.Collection<? extends GrantedAuthority> authorities;

    public UserDetailsImpl(User user) {
        this.user = user;
        this.authorities = user.getRoles().stream()
                .map(Role::getName)
                .filter(java.util.Objects::nonNull)
                .map(String::trim)
                .map(String::toUpperCase)
                .map(name -> new SimpleGrantedAuthority("ROLE_" + name))
                .toList();
    }

    @Override
    public java.util.Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities; // no volvemos a tocar user.getRoles() fuera de sesión
    }

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

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

    public String getFullname() {

        return user.getFullName();
    }

    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() && !user.isDeleted();
    }

    public User getUser() {
        return user;
    }

    public Long getId() {
        return user.getId();
    }

}
