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 org.xyzh.common.vo.UserDeptRoleVO;

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
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);
    }

    /**
     * @description 从LoginDomain创建UserPrincipal（用于从Redis缓存恢复认证信息）
     * @param user 用户信息
     * @param userDeptRoles 用户部门角色列表（来自LoginDomain）
     * @param permissions 权限列表
     * @return UserPrincipal 用户主体
     * @author yslg
     * @since 2025-11-03
     */
    public static UserPrincipal createFromLoginDomain(TbSysUser user, List<UserDeptRoleVO> userDeptRoles, List<TbSysPermission> permissions) {
        // 将UserDeptRoleVO转换为TbSysDeptRole（简化处理，实际使用时UserDeptRoleVO已包含所需信息）
        List<TbSysDeptRole> roles = new ArrayList<>();
        if (userDeptRoles != null) {
            for (UserDeptRoleVO vo : userDeptRoles) {
                TbSysDeptRole role = new TbSysDeptRole();
                role.setRoleID(vo.getRoleID());
                role.setDeptID(vo.getDeptID());
                roles.add(role);
            }
        }
        return new UserPrincipal(user, roles, permissions != null ? permissions : new ArrayList<>());
    }

    @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;
    }
}
