package gaf3.core.gateway

import gaf3.core.cloud.GafCloudConfiguration
import gaf3.core.gateway.filter.factory.JwtParserGatewayFilterFactory
import gaf3.core.jpa.GafJpaConfiguration
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.gateway.webflux.ProxyExchange
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.http.HttpStatus
import org.springframework.http.server.reactive.ServerHttpResponse
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import reactor.core.publisher.Mono


@SpringBootApplication
@Configuration
@Controller
@Import(GafCloudConfiguration::class, GafJpaConfiguration::class)
@ComponentScan(basePackages = ["gaf3.core.services"], basePackageClasses = [GatewayApplication::class])
class GatewayApplication {

    @RequestMapping(value = ["/loopback"])
    @ResponseBody
    fun loopback(res: ServerHttpResponse, proxy: ProxyExchange<ByteArray>): Mono<String> {
        val url = proxy.path()
        println(url)
        res.statusCode = HttpStatus.UNAUTHORIZED
        return Mono.just("No Authorization!")
    }

    @RequestMapping(value = ["/proxy/**"])
    fun forward(res: ServerHttpResponse, proxy: ProxyExchange<ByteArray>): String {
        val url = proxy.path("/proxy")
        log.debug("forward to {}", url);
        return "forward:$url";
    }

    companion object {
        internal val log = LoggerFactory.getLogger(GatewayApplication::class.java)
    }
}

fun main(args: Array<String>) {
    runApplication<GatewayApplication>(*args)
    JwtParserGatewayFilterFactory.doInit()
}
