package com.example.demo.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@ConditionalOnProperty(name = "learning.auth.enabled", havingValue = "true", matchIfMissing = true)
public class LearningSecurityConfig {

    private final LearningJwtFilter learningJwtFilter;

    public LearningSecurityConfig(LearningJwtFilter learningJwtFilter) {
        this.learningJwtFilter = learningJwtFilter;
    }

    @Bean
    public SecurityFilterChain learningSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/", "/home", "/learn/**", "/aop/**", "/api/users/**", "/api/health",
                                "/api/auth/**", "/actuator/**", "/index.html", "/users.html", "/aop.html", "/events.html"
                        ).permitAll()
                        .requestMatchers("/api/secure/**").authenticated()
                        .anyRequest().permitAll()
                )
                .addFilterBefore(learningJwtFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}
