package org.example.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 1. 允许的前端源（必须指定具体地址，不能用*，否则Cookie无法携带）
        config.addAllowedOriginPattern("http://localhost:14564");
        config.addAllowedOriginPattern("http://localhost:8082");
        config.addAllowedOriginPattern("http://localhost:8081");
        config.addAllowedOriginPattern("http://127.0.0.1:8081");
        config.addAllowedOriginPattern("http://192.168.1.51:8081");
        config.addAllowedOriginPattern("http://192.168.1.52:8081");
        config.addAllowedOriginPattern("http://192.168.0.162:14564");
        config.addAllowedOriginPattern("http://192.168.222.12:8081");
        config.addAllowedOriginPattern("http://110.185.161.104:8080");
        config.addAllowedOriginPattern("http://222.211.229.79:8081");
        // 2. 允许跨域携带Cookie（核心）
        config.setAllowCredentials(true);
        // 3. 允许的请求方法（GET/POST等）
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("PATCH");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        // 4. 允许的请求头（如Content-Type、Authorization等）
        config.addAllowedHeader("*");
        // 5. 暴露的响应头（前端需要读取的头，如Set-Cookie）
        config.addExposedHeader("Authorization");
        config.addExposedHeader("Set-Cookie");
        config.addExposedHeader("Content-Disposition");
        config.addExposedHeader("Content-Length");
        config.addExposedHeader("X-Total-Count");
        // 新增：优化预检请求缓存时间（减少OPTIONS请求次数，单位：秒）
        config.setMaxAge(3600L); // 1小时内不再重复发送预检请求

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径生效
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
