package com.devjob.application.config;

import com.devjob.common.security.JwtAuthenticationFilter;
import com.devjob.common.security.JwtProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 지원 서비스 보안. 지원 관련 API는 모두 인증을 요구한다(내 지원 내역 등 개인 데이터).
 * 시즌1처럼 각 서비스가 자기 토큰을 스스로 검증한다(무상태 — 회원 DB 조회 없음).
 * 3장에서 게이트웨이가 인증을 중앙에서 처리하면 이 필터를 제거하고 X-User-Id를 신뢰하도록 바꾼다.
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public JwtProvider jwtProvider(@Value("${jwt.secret}") String secret) {
        return new JwtProvider(secret);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, JwtProvider jwtProvider) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/actuator/**").permitAll()
                        .anyRequest().authenticated()
                )
                .addFilterBefore(new JwtAuthenticationFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
