package cclotus.cloud.gateway.bean

import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import java.net.URI

@Configuration
open class GlobalFilterBean {
    @Bean
    @Order(-1)
    open fun debugLog(): GlobalFilter {
        return GlobalFilter { exchange, chain ->
            val header = exchange.request.headers[HEADER_APP] ?: listOf("")
            val app1 = header[0]
//            val app2 = exchange.getAttribute<String>(HEADER_APP)
            log.debug("[debug log] Host from header: {}", app1)
//            log.debug("[debug log] Host from exchange: {}", app2)
            val requestUrl = exchange.getRequiredAttribute<URI>(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR)
            log.debug("[debug log] Uri from exchange: {}", requestUrl)
            chain.filter(exchange)
        }
    }

    companion object {
        const val HEADER_APP = "X-App"
        internal val log = LoggerFactory.getLogger(GlobalFilterBean::class.java)
    }
}