package com.eitc.framework.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.sign.SaSignUtil;
import com.eitc.common.annotation.InterfaceVerification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;










@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加自定义拦截器
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**"); // 拦截所有路径
        // 可以添加更多拦截器配置
    }
}

class MyInterceptor implements HandlerInterceptor {
    // 实现HandlerInterceptor接口的方法
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.debug("进入拦截器, URL: {}", request.getServletPath());

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 检查请求的方法是否添加了 TokenRequired 注解
        if (!handlerMethod.hasMethodAnnotation(InterfaceVerification.class)) {
            logger.debug("接口未添加 TokenRequired 注解，直接放行");
            return true;
        }
        // 进行 token 验证
        SaSignUtil.checkRequest(SaHolder.getRequest());
        return true; // Token 验证通过，允许请求通过
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 在整个请求结束之后调用，也就是在DispatcherServlet渲染了视图执行
    }
}
