package org.raddatz.familienarchiv.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;

import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.user.CustomUserDetailsService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.annotation.web.configurers.AbstractHttpConfigurer;
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.session.ChangeSessionIdAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfException;
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;

import java.util.Map;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    // @WebMvcTest slices do not include JacksonAutoConfiguration, so ObjectMapper
    // cannot be injected here. A static instance is safe because the response
    // only serializes fixed String keys — no custom naming strategy or module needed.
    private static final ObjectMapper ERROR_WRITER = new ObjectMapper();

    private final CustomUserDetailsService userDetailsService;
    private final Environment environment;

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        // ChangeSessionIdAuthenticationStrategy rotates the session ID via the Servlet 3.1+
        // HttpServletRequest.changeSessionId() — preserves attributes, mints a fresh ID.
        // Used by AuthSessionController.login to defend against session fixation (CWE-384).
        return new ChangeSessionIdAuthenticationStrategy();
    }

    @Bean
    @Order(1)
    public SecurityFilterChain managementFilterChain(HttpSecurity http) throws Exception {
        http
                .securityMatcher("/actuator/**")
                .authorizeHttpRequests(auth -> {
                    // Health and Prometheus are open — Docker health checks and Prometheus scraping need no credentials.
                    auth.requestMatchers("/actuator/health", "/actuator/prometheus").permitAll();
                    // All other actuator endpoints (metrics, info, env, heapdump…) require authentication.
                    auth.anyRequest().authenticated();
                })
                // Explicitly return 401 for any unauthenticated actuator request.
                // Without this override, Spring Security's DelegatingAuthenticationEntryPoint
                // would redirect browser-like clients to the form-login page (302 → /login),
                // making it impossible to distinguish "not authenticated" from "not found" in tests.
                .exceptionHandling(ex -> ex.authenticationEntryPoint(
                        (req, res, e) -> res.setStatus(HttpServletResponse.SC_UNAUTHORIZED)))
                .formLogin(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // CSRF protection via CookieCsrfTokenRepository (NFR-SEC-103).
                // The backend sets an XSRF-TOKEN cookie (not HttpOnly so JS can read it).
                // All state-changing requests must include X-XSRF-TOKEN matching the cookie.
                // See ADR-022 and issue #524 for the full security rationale.
                .csrf(csrf -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()))

                .authorizeHttpRequests(auth -> {
                    // Actuator endpoints are governed by managementFilterChain (@Order(1)) above.
                    auth.requestMatchers("/actuator/health", "/actuator/prometheus").permitAll();
                    // Login is unauthenticated by definition
                    auth.requestMatchers("/api/auth/login").permitAll();
                    // Password reset endpoints are unauthenticated by nature
                    auth.requestMatchers("/api/auth/forgot-password", "/api/auth/reset-password").permitAll();
                    // Invite-based registration endpoints are public
                    auth.requestMatchers("/api/auth/invite/**", "/api/auth/register").permitAll();
                    // E2E test helper (only active under "e2e" profile)
                    auth.requestMatchers("/api/auth/reset-token-for-test").permitAll();
                    // In dev, allow unauthenticated access to the OpenAPI spec and Swagger UI
                    if (environment.matchesProfiles("dev")) {
                        auth.requestMatchers(
                            "/v3/api-docs/**",
                            "/swagger-ui/**",
                            "/swagger-ui.html"
                        ).permitAll();
                    }
                    auth.anyRequest().authenticated();
                })
                // erlaubt pdf im Iframe
                .headers(headers -> headers
                        .frameOptions(frameOptions -> frameOptions.sameOrigin()))
                // Return 401 for unauthenticated requests; 403+CSRF_TOKEN_MISSING for CSRF failures.
                .exceptionHandling(ex -> ex
                        .authenticationEntryPoint(
                                (req, res, e) -> res.setStatus(HttpServletResponse.SC_UNAUTHORIZED))
                        .accessDeniedHandler((req, res, e) -> {
                            res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                            res.setContentType("application/json;charset=UTF-8");
                            ErrorCode code = (e instanceof CsrfException)
                                    ? ErrorCode.CSRF_TOKEN_MISSING
                                    : ErrorCode.FORBIDDEN;
                            res.getWriter().write(ERROR_WRITER.writeValueAsString(Map.of("code", code.name())));
                        }));

        return http.build();
    }
}
