package cn.reghao.tnb.gateway.log;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * HTTP 请求响应日志过滤器
 *
 * @author reghao
 * @date 2024-11-14 10:05:08
 */
@Slf4j
@Component
public class AccessLogFilter implements GlobalFilter, Ordered {
    private final GatewayLogService gatewayLogService;

    public AccessLogFilter(GatewayLogService gatewayLogService) {
        this.gatewayLogService = gatewayLogService;
    }

    /**
     * 自定义 GlobalFilter 的 order 值必须小于 -1，否则 NettyWriteResponseFilter 会在过滤器被调用前完成响应的发送
     *
     * @param
     * @return
     * @date 2025-07-17 16:36:01
     */
    @Override
    public int getOrder() {
        return -100;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        long requestTime = System.currentTimeMillis();

        // 1. 构建包含新 Header 的请求
        ServerHttpRequest newRequest = exchange.getRequest().mutate()
                .header("x-request-id", requestId)
                .header("x-request-time", String.valueOf(requestTime))
                .build();

        // 2. 先生成包含新请求的 Exchange
        ServerWebExchange newExchange = exchange.mutate()
                .request(newRequest)
                .build();

        // 3. 将 newExchange 传给装饰器（关键：传入的是带 Header 的对象）
        ServerHttpResponseDecorator decoratedResponse = recordResponseLog(newExchange);

        return chain.filter(newExchange.mutate().response(decoratedResponse).build());
    }

    /**
     * 记录响应日志
     * 通过 DataBufferFactory 解决响应体分段传输问题。
     */
    private ServerHttpResponseDecorator recordResponseLog(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        return new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    gatewayLogService.setGatewayLog(exchange);

                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        // 合并多个流集合，解决返回体分段传输
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        // 释放内存
                        DataBufferUtils.release(join);
                        String responseBody = new String(content, StandardCharsets.UTF_8);
                        return bufferFactory.wrap(content);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
    }
}
