package com.example.demo.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import com.example.demo.security.JwtAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {   
        http
            .csrf(csrf -> csrf.disable())
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            )
            .authorizeHttpRequests(auth -> auth
                // Swagger/OpenAPI 路径
                .requestMatchers(
                    "/swagger-ui/**", 
                    "/swagger-ui.html", 
                    "/v3/api-docs/**",
                    "/v3/api-docs",
                    "/api-docs/**",
                    "/swagger-resources/**", 
                    "/webjars/**",
                    "/configuration/ui",
                    "/configuration/security",
                    "/swagger-config",
                    "/api/swagger-config"
                ).permitAll()
                // 公共路径
                .requestMatchers(
                    "/login", 
                    "/register", 
                    "/api/public/**", 
                    "/api/auth/**", 
                    "/api/verification/**", 
                    "/api/email/**", 
                    "/api/tencent/**", 
                    "/api/test/**", 
                    "/api/polling/**", 
                    "/api/diagnostic/**", 
                    "/api/polling-diagnostic/**", 
                    "/api/monitor/**", 
                    "/api/health/**", 
                    "/css/**", 
                    "/js/**", 
                    "/h2-console/**"
                ).permitAll()
                .requestMatchers("/api/orders/stats").permitAll()
                .requestMatchers("/api/orders/**").authenticated()
                .requestMatchers("/api/payments/alipay/notify", "/api/payments/alipay/return").permitAll()
                .requestMatchers("/api/payments/lulupay/notify", "/api/payments/lulupay/return").permitAll()
                .requestMatchers("/api/payment/paypal/success", "/api/payment/paypal/cancel").permitAll()
                .requestMatchers("/api/payments/**").authenticated()
                .requestMatchers("/api/image-to-video/**").authenticated()
                .requestMatchers("/api/text-to-video/**").authenticated()
                .requestMatchers("/api/storyboard-video/**").authenticated()
                .requestMatchers("/api/dashboard/**").hasAnyRole("ADMIN", "SUPER_ADMIN")
                .requestMatchers("/api/admin/**").hasAnyRole("ADMIN", "SUPER_ADMIN")
                .requestMatchers("/settings", "/settings/**").hasAnyRole("ADMIN", "SUPER_ADMIN")
                .requestMatchers("/users/**").hasAnyRole("ADMIN", "SUPER_ADMIN")
                .anyRequest().permitAll()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .usernameParameter("email")
                .passwordParameter("password")
                .defaultSuccessUrl("/", true)
                .permitAll()
            )
            .logout(Customizer.withDefaults());

        // 添加JWT过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // H2 控制台需要以下设置  
        http.headers(headers -> headers.frameOptions(frame -> frame.disable()));
        return http.build();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }
    
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList(
            "http://*:*", "https://*:*", "http://*", "https://*",
            "http://*.*", "https://*.*", "http://*.*.*", "https://*.*.*",
            "http://localhost:*", "http://127.0.0.1:*", "http://0.0.0.0:*",
            "https://*.ngrok.io", "https://*.ngrok-free.app",
            "https://*.cloudflare.com", "https://*.vercel.app",
            "https://*.netlify.app", "https://*.herokuapp.com",
            "https://*.github.io", "https://*.gitlab.io",
            "https://vionow.com", "https://www.vionow.com",
            "http://vionow.com", "http://www.vionow.com", "https://*.vionow.com"
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD", "TRACE", "CONNECT"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setExposedHeaders(Arrays.asList("*"));
        configuration.setMaxAge(3600L);

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