package com.spring.infra.security.config;

import java.util.Arrays;

import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
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.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.AnonymousConfigurer;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer;
import org.springframework.security.config.annotation.web.configurers.RequestCacheConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.infra.security.filter.AuthenticationProcessingFilter;
import com.spring.infra.security.filter.JwtAuthenticationFilter;
import com.spring.infra.security.filter.RedirectIfAuthenticatedFilter;
import com.spring.infra.security.handler.SecurityAccessDeniedHandler;
import com.spring.infra.security.handler.SecurityAuthenticationEntryPoint;
import com.spring.infra.security.handler.SignOutHandler;
import com.spring.infra.security.handler.SigninFailureHandler;
import com.spring.infra.security.handler.SigninSuccessHandler;
import com.spring.infra.security.jwt.JwtTokenService;
import com.spring.infra.security.provider.UserAuthenticationProvider;

/**
 * 애플리케이션의 보안 설정을 담당하는 구성 클래스입니다.
 * 
 * <p>이 클래스는 Spring Security를 구성하고 JWT 기반의 인증을 설정합니다.</p>
 * 
 * @author mindol
 * @version 1.0
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
    
    /**
     * Spring Security의 필터 체인을 구성합니다.
     * 
     * @param http HttpSecurity 객체
     * @param tokenService JWT 토큰 서비스
     * @param authenticationEntryPoint JWT 인증 진입점
     * @param accessDeniedHandler JWT 접근 거부 핸들러
     * @return 구성된 SecurityFilterChain
     */
    @Bean
    @Order(1)
    SecurityFilterChain securityFilterChain(
        HttpSecurity http,
        JwtTokenService tokenService,
        SecurityAuthenticationEntryPoint authenticationEntryPoint,
        SecurityAccessDeniedHandler accessDeniedHandler,
        AuthenticationProcessingFilter authenticationProcessingFilter
    ) throws Exception {
        http
            .headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin))
            .csrf(CsrfConfigurer::disable)
            .httpBasic(HttpBasicConfigurer::disable)
            .formLogin(FormLoginConfigurer::disable)
            .anonymous(AnonymousConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
                .antMatchers(Arrays.stream(PermittedURI.values()).map(PermittedURI::getUri).toArray(String[]::new)).permitAll()
                .anyRequest().authenticated()
            )
            .logout(logout -> logout
                .logoutUrl(PermittedURI.USER_SIGN_OUT.getUri())
                .addLogoutHandler(new SignOutHandler(tokenService))
                .logoutSuccessUrl(PermittedURI.ROOT_URI.getUri())
                .invalidateHttpSession(true))
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .addFilterBefore(
                authenticationProcessingFilter, 
                UsernamePasswordAuthenticationFilter.class
            )
            .addFilterAfter(
                new JwtAuthenticationFilter(tokenService), 
                AuthenticationProcessingFilter.class
            )
            .addFilterAfter(
                new RedirectIfAuthenticatedFilter(),
                JwtAuthenticationFilter.class
            )
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
            );
        return http.build();
    }

    /**
     * 특정 요청에 대해 보안 검사를 무시하도록 설정합니다.
     * 
     * @return 구성된 SecurityFilterChain
     */
    @Bean
    @Order(0)
    SecurityFilterChain resources(HttpSecurity http) throws Exception {
        return http.requestMatchers(matchers -> matchers
                    .requestMatchers(PathRequest.toStaticResources().atCommonLocations()))
                    .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll())
                    .requestCache(RequestCacheConfigurer::disable)
                    .securityContext(AbstractHttpConfigurer::disable)
                    .sessionManagement(AbstractHttpConfigurer::disable)
                    .build();
    }

    /**
     * 비밀번호 인코더를 구성합니다.
     * 
     * @return PasswordEncoder 객체
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
	AuthenticationManager authenticationManager(UserAuthenticationProvider provider) {
		return new ProviderManager(provider);
	}

    @Bean
	AuthenticationProcessingFilter authenticationProcessingFilter(
        ObjectMapper objectMapper,
        AuthenticationManager authenticationManager,
        SigninSuccessHandler signinSuccessHandler,
        SigninFailureHandler signinFailureHandler
    ) {
        var filter = new AuthenticationProcessingFilter(objectMapper);
        filter.setAuthenticationManager(authenticationManager);
        filter.setAuthenticationSuccessHandler(signinSuccessHandler);
        filter.setAuthenticationFailureHandler(signinFailureHandler);
		return filter;
	}

}
