package dp.kotul.starter.autoconfig

import dp.kotul.starter.filter.CorrelationHeaderAndLoggingFilter
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.web.filter.CommonsRequestLoggingFilter
import javax.servlet.Filter

@Configuration
class FilterAutoConfiguration(val beanFactory: AutowireCapableBeanFactory) {

    @Bean
    fun correlationFilterRegistration(): FilterRegistrationBean<Filter> {
        val registration = FilterRegistrationBean<Filter>()
        val filter = CorrelationHeaderAndLoggingFilter()
        beanFactory.autowireBean(filter)
        registration.filter = filter
        registration.addUrlPatterns("/*")
        registration.order = Ordered.HIGHEST_PRECEDENCE
        return registration
    }

    @Bean
    @ConditionalOnProperty(name = ["logging.filter.enabled"], havingValue = "true")
    fun loggingFilterRegistration(): FilterRegistrationBean<Filter> {
        val registration = FilterRegistrationBean<Filter>()

        val loggingFilter = CommonsRequestLoggingFilter()
        loggingFilter.setIncludeClientInfo(true)
        loggingFilter.setIncludeQueryString(true)
        loggingFilter.setIncludePayload(true)
        loggingFilter.setMaxPayloadLength(100000)
        loggingFilter.setIncludeHeaders(false)

        beanFactory.autowireBean(loggingFilter)
        registration.filter = loggingFilter
        registration.addUrlPatterns("/*")
        registration.order = Ordered.HIGHEST_PRECEDENCE + 1

        return registration
    }
}
