package com.mzh.library.entity;

import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class AuthenticatedUser implements Serializable {
    private static final long serialVersionUID = 1L;

    private final long id;
    private final String username;
    private final String displayName;
    private final Role role;
    private final Set<Permission> permissions;

    public AuthenticatedUser(long id, String username, String displayName, Role role, Set<Permission> permissions) {
        this.id = id;
        this.username = username;
        this.displayName = displayName;
        this.role = role;
        this.permissions = Collections.unmodifiableSet(new LinkedHashSet<>(permissions));
    }

    public static AuthenticatedUser from(User user, Set<Permission> permissions) {
        return new AuthenticatedUser(
            user.getId(),
            user.getUsername(),
            user.getDisplayName(),
            user.getRole(),
            permissions
        );
    }

    public long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getDisplayName() {
        return displayName;
    }

    public Role getRole() {
        return role;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public Set<String> getPermissionCodes() {
        return permissions.stream()
            .map(Permission::getCode)
            .collect(Collectors.toCollection(LinkedHashSet::new));
    }
}
