package com.zioinfo.signage.config;

import com.zioinfo.signage.auth.JwtFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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;

/**
 * Spring Security 6 — JWT 무상태 인증 + 멀티테넌트 RBAC.
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtFilter jwtFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .cors(cors -> {})
            .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                // 인증 불필요
                .requestMatchers("/api/auth/**").permitAll()
                // UIWS system 이식: 공통 룩업(부서/거래처 트리 등 비민감) 공개 조회
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/actuator/health").permitAll()
                // 정적 리소스 (React SPA)
                .requestMatchers(HttpMethod.GET, "/", "/index.html", "/assets/**", "/*.js", "/*.css", "/*.ico").permitAll()

                // 관리자 전용
                .requestMatchers("/api/tenants/**").hasRole("ADMIN")
                .requestMatchers("/api/users/**").hasAnyRole("ADMIN", "MANAGER")
                .requestMatchers("/api/firmware/**").hasAnyRole("ADMIN", "MANAGER")
                // UIWS system(권한관리: 사용자/역할/메뉴/부서/거래처/코드/프로그램) — 관리자/매니저 전용
                // (일반 /api/** 메서드 규칙보다 먼저 평가되도록 상단 배치)
                .requestMatchers("/api/system/**").hasAnyRole("ADMIN", "MANAGER")
                // admin 보조: 감사로그 조회·설정 조회 = ADMIN/MANAGER, 설정 변경 = ADMIN
                // (아래 일반 PUT /api/** 규칙보다 먼저 평가되도록 상단 배치)
                .requestMatchers(HttpMethod.PUT, "/api/admin/settings/**").hasRole("ADMIN")
                // AI 플랫폼(LLM provider) 설정 — 조회/갱신/테스트 모두 ADMIN 전용 (상단 배치로 우선 평가)
                .requestMatchers("/api/admin/ai-config/**").hasRole("ADMIN")
                .requestMatchers("/api/admin/**").hasAnyRole("ADMIN", "MANAGER")
                // AI 기법 토글 변경 = MANAGER+ (조회/실행은 일반 인증 사용자) — 상단 배치로 우선 평가
                .requestMatchers(HttpMethod.PUT, "/api/ai/rag/toggles/**").hasAnyRole("ADMIN", "MANAGER")
                .requestMatchers(HttpMethod.DELETE, "/api/**").hasAnyRole("ADMIN", "MANAGER")
                .requestMatchers(HttpMethod.POST, "/api/**").hasAnyRole("ADMIN", "MANAGER", "USER")
                .requestMatchers(HttpMethod.PUT, "/api/**").hasAnyRole("ADMIN", "MANAGER", "USER")

                // 그 외 GET은 인증 사용자 허용
                .anyRequest().authenticated()
            )
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

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

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