package com.lingyue.common.util;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 安全工具类
 * 
 * 用于从请求上下文中获取当前用户信息
 * 
 * @author lingyue
 * @since 2026-01-24
 */
@Slf4j
public class SecurityUtils {
    
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    
    /**
     * 获取当前用户ID
     * 
     * @return 用户ID，未登录返回null
     */
    public static String getCurrentUserId() {
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        return JwtUtil.getUserIdFromToken(token);
    }
    
    /**
     * 获取当前用户ID（使用指定密钥）
     * 
     * @param jwtSecret JWT密钥
     * @return 用户ID，未登录返回null
     */
    public static String getCurrentUserId(String jwtSecret) {
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        return JwtUtil.getUserIdFromToken(token, jwtSecret);
    }
    
    /**
     * 获取当前用户名
     * 
     * @return 用户名，未登录返回null
     */
    public static String getCurrentUsername() {
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        Claims claims = JwtUtil.parseToken(token);
        return claims != null ? (String) claims.get("username") : null;
    }
    
    /**
     * 获取当前用户名（使用指定密钥）
     * 
     * @param jwtSecret JWT密钥
     * @return 用户名，未登录返回null
     */
    public static String getCurrentUsername(String jwtSecret) {
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        Claims claims = JwtUtil.parseToken(token, jwtSecret);
        return claims != null ? (String) claims.get("username") : null;
    }
    
    /**
     * 获取当前Token
     * 
     * @return Token，未登录返回null
     */
    public static String getTokenFromRequest() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        String authorization = request.getHeader(AUTHORIZATION_HEADER);
        if (authorization != null && authorization.startsWith(BEARER_PREFIX)) {
            return authorization.substring(BEARER_PREFIX.length());
        }
        return null;
    }
    
    /**
     * 获取当前请求
     * 
     * @return HttpServletRequest，非Web环境返回null
     */
    public static HttpServletRequest getRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attributes != null ? attributes.getRequest() : null;
        } catch (Exception e) {
            log.debug("获取HttpServletRequest失败（可能不在Web请求上下文中）: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 检查当前用户是否已登录
     * 
     * @return 是否已登录
     */
    public static boolean isAuthenticated() {
        return getCurrentUserId() != null;
    }
    
    /**
     * 获取客户端IP地址
     * 
     * @return IP地址
     */
    public static String getClientIpAddress() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
    
    /**
     * 获取User-Agent
     * 
     * @return User-Agent
     */
    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        return request != null ? request.getHeader("User-Agent") : null;
    }
}
