package me.qwq.doghouse.component;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import me.qwq.doghouse.annotation.RequireSession;

@Aspect
@Component
public class RequireSessionAspect {

    @Before("@annotation(requireSession)")
    public void verifySession(JoinPoint joinPoint, RequireSession requireSession) {

        // 检查是否在 DispatcherServlet 控制下
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        if (!(attrs instanceof ServletRequestAttributes servletAttrs)) {
            throw new IllegalStateException(
                    joinPoint.getSignature() + 
                    " 必须在 Web 请求上下文中调用（未检测到 HttpServletRequest）");
        }

        HttpServletRequest request = servletAttrs.getRequest();
        HttpSession session = request.getSession(requireSession.create());

        if (session == null) {
            throw new IllegalStateException(
                    joinPoint.getSignature() + 
                    " 调用时不允许创建 Session，但未检测到有效 Session");
        }
    }
}