package com.zsElectric.boot.common.util.electric.queryToken;

import com.zsElectric.boot.core.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@RequiredArgsConstructor
public class TokenValidationAspect {
    
    private final JwtTokenUtil jwtTokenUtil;
    
    @Around("@annotation(tokenRequired)")
    public Object validateToken(ProceedingJoinPoint joinPoint, TokenRequired tokenRequired) throws Throwable {
        // 获取HttpServletRequest
        HttpServletRequest request = getHttpServletRequest(joinPoint);
        if (request == null) {
            throw new RuntimeException("无法获取HttpServletRequest");
        }
        // 验证Token
        String token = extractTokenFromRequest(request);

        if (token == null || !jwtTokenUtil.validateToken(token)) {
            throw new BusinessException("Token验证失败");
        }
        return joinPoint.proceed();
    }
    

    
    private HttpServletRequest getHttpServletRequest(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof HttpServletRequest) {
                return (HttpServletRequest) arg;
            }
        }
        
        // 如果从方法参数中找不到HttpServletRequest，则尝试从RequestContextHolder获取
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            return attributes.getRequest();
        } catch (IllegalStateException e) {
            // RequestContextHolder中没有可用的请求上下文
            return null;
        }
    }
    
    private String extractTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}
