package com.devjob.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.Instant;

/**
 * 모든 요청/응답을 로깅하는 글로벌 필터.
 *
 * Gateway를 통과하는 모든 라우트에 자동으로 적용된다 (라우트별로 filters에
 * 등록할 필요 없음). 어떤 요청이 어느 경로로 들어와서 얼마나 걸렸는지를
 * 한 곳에서 확인할 수 있다.
 */
@Slf4j
@Component
public class LoggingGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        Instant start = Instant.now();

        log.info("[Gateway] --> {} {}", request.getMethod(), request.getURI().getPath());

        return chain.filter(exchange).doFinally(signalType -> {
            Duration elapsed = Duration.between(start, Instant.now());
            int statusCode = exchange.getResponse().getStatusCode() != null
                    ? exchange.getResponse().getStatusCode().value()
                    : 0;
            log.info("[Gateway] <-- {} {} ({}ms) status={}",
                    request.getMethod(), request.getURI().getPath(), elapsed.toMillis(), statusCode);
        });
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
