package org.mte.numecoeval.expositiondonneesentrees.infrastructure.config.security;

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.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Configuration Spring Security
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Value("${numecoeval.urls.allowed:}")
    private String[] urlsAllowed;

    /**
     * Configuration pour les endpoints avec une session DNC.
     */
    @Bean
    SecurityFilterChain globalFilterChain(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors()
                .and()
                .authorizeHttpRequests(authz -> authz
                        // Healthcheck Actuator
                        .requestMatchers("/health").permitAll()
                        // application
                        .requestMatchers("/entrees/**").permitAll()
                        // Springdoc-openapi
                        .requestMatchers("/v3/api-docs/**").permitAll()
                        .requestMatchers("/swagger-ui/**").permitAll()
                        .requestMatchers("/swagger-ui.html").permitAll()
                        .requestMatchers("/openapi.yaml").permitAll()
                )
                .csrf().disable()
                .formLogin().disable()
        ;
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(urlsAllowed));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTION"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
