package de.assecutor.votianlt.security;

import de.assecutor.votianlt.model.User;
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.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Custom UserDetails implementation that holds a reference to the MongoDB User
 * entity. This allows access to the complete User object from the session
 * without additional database queries.
 */
public class CustomUserPrincipal implements UserDetails {

    private final User user; // MongoDB User entity

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

    /**
     * Get the complete MongoDB User entity
     */
    public User getUser() {
        return user;
    }

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

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

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

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<String> roles = user.getRoles();
        if (roles != null && !roles.isEmpty()) {
            return roles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toList());
        }
        // Default role if no roles are set
        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
    }

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

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

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