package com.zhentao.security;

import com.zhentao.entity.AdminUser;
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.List;
import java.util.stream.Collectors;

/**
 * Admin用户详情，实现Spring Security的UserDetails接口
 */
public class AdminUserDetails implements UserDetails {
    
    private final AdminUser adminUser;
    private final List<GrantedAuthority> authorities;
    private final boolean isSuperAdmin;
    
    public AdminUserDetails(AdminUser adminUser, List<String> permissions, boolean isSuperAdmin) {
        this.adminUser = adminUser;
        this.isSuperAdmin = isSuperAdmin;
        
        // 将权限字符串转换为GrantedAuthority
        if (permissions != null && !permissions.isEmpty()) {
            this.authorities = permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        } else {
            this.authorities = Collections.emptyList();
        }
    }
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    
    @Override
    public String getPassword() {
        return adminUser.getPassword();
    }
    
    @Override
    public String getUsername() {
        return adminUser.getUsername();
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return adminUser.getStatus() != null && adminUser.getStatus() == 1;
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return adminUser.getStatus() != null && adminUser.getStatus() == 1;
    }
    
    public AdminUser getAdminUser() {
        return adminUser;
    }
    
    public boolean isSuperAdmin() {
        return isSuperAdmin;
    }
    
    public Integer getUserId() {
        return adminUser.getId();
    }
}

