package org.xyzh.auth.domain;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.dto.dept.TbSysDeptRole;
import org.xyzh.common.dto.permission.TbSysPermission;
import org.xyzh.common.core.enums.UserStatus;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description    UserPrincipal.java文件描述 用户主体类
 * @filename    UserPrincipal.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
public class UserPrincipal implements UserDetails {

    private TbSysUser user;
    private List<TbSysDeptRole> roles;
    private List<TbSysPermission> permissions;

    private UserPrincipal(TbSysUser user, List<TbSysDeptRole> roles, List<TbSysPermission> permissions) {
        this.user = user;
        this.roles = roles;
        this.permissions = permissions;
    }

    public static UserPrincipal create(TbSysUser user, List<TbSysDeptRole> roles, List<TbSysPermission> permissions) {
        return new UserPrincipal(user, roles, permissions);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 角色权限
        List<GrantedAuthority> roleAuthorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getID()))
                .collect(Collectors.toList());

        // 功能权限
        List<GrantedAuthority> permissionAuthorities = permissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getCode()))
                .collect(Collectors.toList());

        return Stream.concat(roleAuthorities.stream(), permissionAuthorities.stream())
                .collect(Collectors.toList());
    }

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

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

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

    @Override
    public boolean isAccountNonLocked() {
        UserStatus status = UserStatus.fromCode(String.valueOf(user.getStatus()));
        return status != UserStatus.LOCKED;
    }

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

    @Override
    public boolean isEnabled() {
        UserStatus status = UserStatus.fromCode(String.valueOf(user.getStatus()));
        return status == UserStatus.NORMAL;
    }

    public TbSysUser getUser() {
        return user;
    }

    public List<TbSysDeptRole> getRoles() {
        return roles;
    }

    public List<TbSysPermission> getPermissions() {
        return permissions;
    }
}
