package com.seer.teach.filter.route;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.net.URI;

@Slf4j
@Configuration
public class RouteLoggerConfig {

    @Bean
    public GlobalFilter detailedRouteLogger() {

        return (exchange, chain) -> {
            Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

            if (route != null) {
                log.info("├── Route ID: {}", route.getId());
                log.info("├── Target URI: {}", route.getUri());
                log.info("└── Original Path: {}", exchange.getRequest().getPath());

                URI finalUri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
                if (finalUri != null && !route.getUri().equals(finalUri)) {
                    log.info("Rewritten URL: {}", finalUri);
                }
            }

            return chain.filter(exchange)
                    .then(Mono.fromRunnable(() -> {
                        if (route != null) {
                            log.info("Forwarded to: {} [Status: {}]",
                                    exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR),
                                    exchange.getResponse().getStatusCode());
                        }
                    }));
        };
    }
}