package com.honey.honey.config;

import com.honey.honey.security.admin.AdminDetailsService;
import com.honey.honey.security.admin.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.beans.factory.annotation.Value;
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;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class AdminSecurityConfig {

    @Value("${FRONTEND_URL:}")
    private String frontendUrl;

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final AdminDetailsService adminDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider adminAuthenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(adminDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public AuthenticationManager adminAuthenticationManager() {
        return new ProviderManager(adminAuthenticationProvider());
    }

    /**
     * Swagger/OpenAPI docs: permitAll with highest precedence so the default Spring Boot chain
     * (which requires auth for /**) never handles these paths. Includes webjars and resources
     * so the UI can load CSS/JS. Also matches /api/swagger-ui/** and /api/v3/api-docs/** so
     * Swagger behind nginx at a secret path (e.g. /secret/swagger-ui/ -> /api/swagger-ui/) is public.
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain swaggerSecurityFilterChain(HttpSecurity http) throws Exception {
        RequestMatcher swaggerMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher("/swagger-ui/**"),
                new AntPathRequestMatcher("/swagger-ui.html"),
                new AntPathRequestMatcher("/v3/api-docs"),
                new AntPathRequestMatcher("/v3/api-docs/**"),
                new AntPathRequestMatcher("/webjars/**"),
                new AntPathRequestMatcher("/swagger-resources/**"),
                new AntPathRequestMatcher("/configuration/**"),
                new AntPathRequestMatcher("/api/swagger-ui/**"),
                new AntPathRequestMatcher("/api/swagger-ui.html"),
                new AntPathRequestMatcher("/api/v3/api-docs"),
                new AntPathRequestMatcher("/api/v3/api-docs/**"),
                new AntPathRequestMatcher("/api/webjars/**"),
                new AntPathRequestMatcher("/api/swagger-resources/**"),
                new AntPathRequestMatcher("/api/configuration/**")
        );
        http
                .securityMatcher(swaggerMatcher)
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain adminSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/admin/**")
            .csrf(csrf -> csrf.disable())
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/admin/login", "/api/admin/chatwoot-session").permitAll()
                .requestMatchers("/api/admin/users/**").hasAnyRole("ADMIN", "SUPPORT")
                .requestMatchers("/api/admin/payments/**").hasAnyRole("ADMIN", "SUPPORT")
                .requestMatchers("/api/admin/payouts/**").hasAnyRole("ADMIN", "SUPPORT")
                .requestMatchers("/api/admin/rooms/**").hasAnyRole("ADMIN")
                .requestMatchers("/api/admin/configurations/**").hasAnyRole("ADMIN")
                .requestMatchers("/api/admin/tickets/**").hasAnyRole("ADMIN")
                .requestMatchers("/api/admin/quick-answers/**").hasAnyRole("ADMIN")
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().denyAll()
            )
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        List<String> allowedOrigins = Stream.concat(
                Stream.of(
                    "http://localhost:5173",
                    "http://localhost:3000"
                ),
                frontendUrl != null && !frontendUrl.isBlank()
                    ? Arrays.stream(frontendUrl.split("\\s*,\\s*")).filter(s -> !s.isBlank())
                    : Stream.empty()
        ).distinct().collect(Collectors.toList());

        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(allowedOrigins);
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

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

