package test05.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import test05.interceptor.LoginCheckInterceptor;


/**
 * 配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final LoginCheckInterceptor loginCheckInterceptor;
    private final Environment environment;

    // 构造函数注入，登陆检查拦截器
    @Autowired
    WebConfig(LoginCheckInterceptor loginCheckInterceptor, Environment environment){
        this.loginCheckInterceptor = loginCheckInterceptor;
        this.environment = environment;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginCheckInterceptor)
                .addPathPatterns("/*Action/**")
                .excludePathPatterns("/userAction/login", "/userAction/logout");
    }

    @Override
    public void addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry registry) {
        // 仅在开发环境启用跨域
        String[] activeProfiles = environment.getActiveProfiles();
        boolean isDev = false;
        
        if (activeProfiles.length == 0) {
            // 如果没有指定profile，默认使用dev
            isDev = true;
        } else {
            for (String profile : activeProfiles) {
                if ("dev".equals(profile) || "development".equals(profile) || "test".equals(profile)) {
                    isDev = true;
                    break;
                }
            }
        }
        
        if (isDev) {
            registry.addMapping("/**") // 允许所有路径
                    .allowedOriginPatterns("*") // 允许所有来源
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                    .allowedHeaders("*") // 允许所有请求头
                    .allowCredentials(true) // 允许发送cookie
                    .maxAge(3600); // 预检请求的有效期
        }
    }
}
