package com.test.bijihoudaun.config;

import com.test.bijihoudaun.interceptor.CaptchaValidationInterceptor;
import com.test.bijihoudaun.interceptor.RateLimitInterceptor;
import com.test.bijihoudaun.interceptor.ReplayAttackInterceptor;
import com.test.bijihoudaun.interceptor.XSSInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private CaptchaValidationInterceptor captchaValidationInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(false)
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:uploads/");
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 限流拦截器（最先执行）
        registry.addInterceptor(new RateLimitInterceptor())
                .addPathPatterns("/**")
                .order(1);

        // 防重放攻击拦截器
        registry.addInterceptor(new ReplayAttackInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/doc.html", "/webjars/**", "/v3/api-docs/**")
                .order(2);

        // XSS 过滤拦截器（过滤请求参数和请求头）
        registry.addInterceptor(new XSSInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/api/images/upload", "/doc.html", "/webjars/**", "/v3/api-docs/**")
                .order(3);

        // 验证码验证拦截器
        registry.addInterceptor(captchaValidationInterceptor)
                .addPathPatterns("/**")
                .order(4);
    }
}
