package com.qqchen.deploy.backend.framework.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Security 工具类
 * 提供获取当前用户信息、权限检查等功能
 *
 * @author qqchen
 * @date 2025-10-25
 */
public class SecurityUtils {
    
    /**
     * 获取当前登录用户名
     *
     * @return 当前用户名，未认证时返回 "SYSTEM"
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return "SYSTEM";
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return principal.toString();
    }
    
    /**
     * 获取当前用户ID（字符串类型）
     * 
     * @return 当前用户ID，未认证时返回 "system"
     */
    public static String getCurrentUserIdAsString() {
        Long userId = getCurrentUserId();
        return userId != null ? userId.toString() : "system";
    }
    
    /**
     * 获取当前用户ID（Long 类型）
     * 
     * @return 当前用户ID，未认证时返回 null
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomUserDetails) {
            return ((CustomUserDetails) principal).getUserId();
        }
        
        // 兼容标准 UserDetails（用于测试或特殊场景）
        return null;
    }
    
    /**
     * 获取当前租户ID
     * 
     * @return 当前租户ID，未认证或未设置时返回 null
     */
    public static Long getCurrentTenantId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomUserDetails) {
            return ((CustomUserDetails) principal).getTenantId();
        }
        
        return null;
    }
    
    /**
     * 获取当前部门ID
     * 
     * @return 当前部门ID，未认证或未设置时返回 null
     */
    public static Long getCurrentDepartmentId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof CustomUserDetails) {
            return ((CustomUserDetails) principal).getDepartmentId();
        }
        
        return null;
    }
    
    /**
     * 检查是否有指定权限
     *
     * @param permission 权限标识
     * @return 是否拥有该权限
     */
    public static boolean hasPermission(String permission) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && 
               authentication.isAuthenticated() && 
               authentication.getAuthorities().stream()
                   .anyMatch(auth -> auth.getAuthority().equals(permission));
    }
    
    /**
     * 检查是否已认证
     *
     * @return 是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated();
    }
} 