package com.stdproject.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

/**
 * Spring Security配置类
 *
 * @author StdProject
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {

    @Autowired
    private PasswordEncoder passwordEncoder;

    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final CustomUserDetailsService customUserDetailsService;

    @Value("${spring.security.jwt.enabled:true}")
    private boolean jwtEnabled;

    @Value("${spring.security.cors.allowed-origins:http://localhost:3000,http://localhost:8080}")
    private List<String> allowedOrigins;

    @Value("${spring.security.cors.max-age:3600}")
    private Long corsMaxAge;

    // 公开路径配置
    private static final String[] PUBLIC_PATHS = {
            "/auth/**",
            "/api/public/**",
            "/swagger-ui/**",
            "/v3/api-docs/**",
            "/swagger-ui.html",
            "/webjars/**",
            "/favicon.ico",
            "/error",
            "/actuator/health",
            "/actuator/info"
    };


    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    /**
     * CORS配置
     * 更安全的CORS配置，支持配置化的允许源
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        // 设置允许的源，支持配置化
        configuration.setAllowedOrigins(allowedOrigins);

        // 设置允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList(
                "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
        ));

        // 设置允许的请求头
        configuration.setAllowedHeaders(Arrays.asList(
                "Authorization", "Content-Type", "X-Requested-With",
                "Accept", "Origin", "Access-Control-Request-Method",
                "Access-Control-Request-Headers", "X-CSRF-TOKEN"
        ));

        // 设置暴露的响应头
        configuration.setExposedHeaders(Arrays.asList(
                "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
                "Authorization", "Content-Disposition"
        ));

        configuration.setAllowCredentials(true);
        configuration.setMaxAge(corsMaxAge);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    /**
     * 安全过滤器链配置
     * 增强的安全配置，包含安全头和更完善的认证授权
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // CORS配置
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))

            // 禁用CSRF（因为使用JWT，无状态）
            .csrf(csrf -> csrf.disable())

            // 会话管理配置
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .maximumSessions(1)
                .maxSessionsPreventsLogin(false)
            )

            // 异常处理配置
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            )

            // 安全头配置
            .headers(headers -> headers
                // 禁用iframe嵌入,防止点击劫持攻击
                .frameOptions().deny()
                // 设置X-Content-Type-Options头为nosniff,防止MIME类型嗅探攻击
                .contentTypeOptions().and()
                // 设置Referrer Policy为strict-origin-when-cross-origin
                // 跨域请求时只发送源(origin),同源请求发送完整referrer
                .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
                // 注意：已移除HSTS配置，不再强制使用HTTPS
            );

        // 根据配置决定是否启用JWT认证
        if (jwtEnabled) {
            http.authorizeHttpRequests(authz -> authz
                    // 公开接口，无需认证
                    .requestMatchers(PUBLIC_PATHS).permitAll()
                    // 管理员接口需要管理员权限
                    .requestMatchers("/api/admin/**").hasRole("ADMIN")
                    // 其他所有请求都需要认证
                    .anyRequest().authenticated()
            );

            // 添加JWT过滤器
            http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        } else {
            // 如果禁用JWT认证，则允许所有请求（开发环境）
            http.authorizeHttpRequests(authz -> authz
                    .anyRequest().permitAll()
            );
        }

        return http.build();
    }
}
