package com.betriebsratkanzlei.legalconsenthub.config

import com.betriebsratkanzlei.legalconsenthub.security.CustomJwtAuthenticationConverter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.invoke
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder
import org.springframework.security.web.SecurityFilterChain
import org.springframework.http.HttpMethod

@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    @Order(1)
    fun publicApiSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            securityMatcher("/swagger-ui/**", "/v3/**", "/actuator/**")
            csrf { disable() }
            authorizeHttpRequests {
                authorize("/swagger-ui/**", permitAll)
                authorize("/v3/**", permitAll)
                authorize("/actuator/**", permitAll)
                authorize(anyRequest, denyAll)
            }
        }
        return http.build()
    }

    @Bean
    @Order(2)
    fun protectedApiSecurityFilterChain(
        http: HttpSecurity,
        customJwtAuthenticationConverter: CustomJwtAuthenticationConverter
    ): SecurityFilterChain {
        http {
            csrf { disable() }
            authorizeHttpRequests {
                // Allow user registration without authentication
                authorize(HttpMethod.POST, "/users", permitAll)
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt { jwtAuthenticationConverter = customJwtAuthenticationConverter }
            }
        }
        return http.build()
    }

    @Bean
    fun jwtDecoder(): JwtDecoder {
        return NimbusJwtDecoder.withJwkSetUri("http://192.168.178.114:3001/api/auth/jwks")
            .jwsAlgorithm(SignatureAlgorithm.ES512).build()
    }
}
