package com.dowstats.configuration;

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.web.SecurityFilterChain
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource


@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http.cors {httpSecurityCorsConfigurer ->
            val configuration = CorsConfiguration()
            configuration.allowedOrigins = listOf("*")
            configuration.allowedMethods = listOf("*")
            configuration.allowedHeaders = listOf("*")
            val source: UrlBasedCorsConfigurationSource = UrlBasedCorsConfigurationSource()
            source.registerCorsConfiguration("/**", configuration)
            httpSecurityCorsConfigurer.configurationSource(source)
        }
        .csrf().disable()
        .authorizeHttpRequests {
            it.requestMatchers("/admin/**")
                .hasRole("ADMIN")
            it.requestMatchers("/api/v1/**")
                .anonymous()
            it.requestMatchers("/login")
                .permitAll()
                .anyRequest()
                .authenticated()
        }

        return http.build()
    }
}