package com.zioinfo.hrm.config;

import com.zioinfo.hrm.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;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * GUARDiA HRM 보안 설정 — JWT 무상태 인증 + RBAC.
 * RBAC 역할(상위→하위): SUPERADMIN ⊃ MANAGER ⊃ HR_STAFF ⊃ VIEWER.
 */
@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 -> cors.configurationSource(corsConfigurationSource()))
            .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/hrm/auth/**").permitAll()
                // UIWS 로그인 보조 3종(회원가입·아이디찾기·비번초기화) — 로그인 전 무인증 접근.
                .requestMatchers("/api/auth/**").permitAll()
                // UIWS system: 가입 화면 공개 조회(부서/회사 GET) — permitAll.
                .requestMatchers(HttpMethod.GET, "/api/public/**").permitAll()
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/api/hrm/docs/**", "/api/hrm/swagger/**").permitAll()
                .requestMatchers("/", "/index.html", "/assets/**", "/favicon.ico").permitAll()

                // UIWS system(권한관리): 조회는 MANAGER 이상, 변경은 SUPERADMIN.
                .requestMatchers(HttpMethod.GET, "/api/system/**").hasAnyRole("SUPERADMIN", "MANAGER")
                .requestMatchers("/api/system/**").hasRole("SUPERADMIN")

                .requestMatchers("/api/hrm/admin/users/**").hasRole("SUPERADMIN")
                .requestMatchers(HttpMethod.GET, "/api/hrm/admin/settings").hasAnyRole("SUPERADMIN", "MANAGER")
                .requestMatchers("/api/hrm/admin/settings/**").hasRole("SUPERADMIN")
                .requestMatchers("/api/hrm/admin/audit").hasAnyRole("SUPERADMIN", "MANAGER")
                .requestMatchers("/api/hrm/admin/**").hasRole("SUPERADMIN")

                // 급여처리, 평가 승인 — HR_STAFF 이상 (서비스에서 MANAGER+ 추가 가드)
                .requestMatchers(HttpMethod.POST,   "/api/hrm/**").hasAnyRole("SUPERADMIN", "MANAGER", "HR_STAFF")
                .requestMatchers(HttpMethod.PUT,    "/api/hrm/**").hasAnyRole("SUPERADMIN", "MANAGER", "HR_STAFF")
                .requestMatchers(HttpMethod.PATCH,  "/api/hrm/**").hasAnyRole("SUPERADMIN", "MANAGER", "HR_STAFF")
                .requestMatchers(HttpMethod.DELETE, "/api/hrm/**").hasAnyRole("SUPERADMIN", "MANAGER", "HR_STAFF")
                .requestMatchers(HttpMethod.GET,    "/api/hrm/**").hasAnyRole("SUPERADMIN", "MANAGER", "HR_STAFF", "VIEWER")

                .anyRequest().authenticated()
            )
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(List.of("*"));
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(List.of("*"));
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

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

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