package dp.kotul.starter.autoconfig

import dp.kotul.jwt.JwtParser
import dp.kotul.starter.filter.AuthorizationInterceptor
import dp.kotul.starter.properties.AuthInterceptorProperties
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@EnableWebMvc
@Configuration
@EnableConfigurationProperties(AuthInterceptorProperties::class)
class AuthAutoConfiguration(val jwtParser: JwtParser, val authProperties: AuthInterceptorProperties) : WebMvcConfigurer {

    val defaultExcludedUrls = listOf(
        "/v2/api-docs", "/swagger-ui.html", "/configuration/ui/**", "/webjars/**",
        "/swagger-resources/**", "/error", "/favicon.ico", "/csrf", "/swagger-ui/**"
    )

    @Bean
    @ConditionalOnMissingBean
    fun authorizationInterceptor(): AuthorizationInterceptor {
        return AuthorizationInterceptor(jwtParser)
    }

    override fun addInterceptors(registry: InterceptorRegistry) {
        if (authProperties.enabled) {
            registry.addInterceptor(authorizationInterceptor())
                .addPathPatterns(authProperties.urlPatterns)
                .excludePathPatterns(defaultExcludedUrls + authProperties.excludeUrlPatterns)
        }
    }
}
