package com.backendsys.modules.common.Filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.web.reactive.function.client.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class WebClientFilter {

    // 请求/响应拦截器
    public static ExchangeFilterFunction logFilter = (request, next) -> {
        System.out.println("[logRequestFilter] Request: " + request.method() + " " + request.url());
        return next.exchange(request).flatMap(response -> {

            // 读取并缓存整个响应体
            return DataBufferUtils.join(response.bodyToFlux(DataBuffer.class))
                .flatMap(dataBuffer -> {
                    // 提取字节数组并释放缓冲区
                    byte[] bodyBytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bodyBytes);
                    DataBufferUtils.release(dataBuffer);

                    // 记录响应体
                    String bodyStr = new String(bodyBytes, StandardCharsets.UTF_8);
//                    System.out.println("[logRequestFilter] Response Body: " + bodyStr);
                    System.out.println("[logRequestFilter] Response Body: " + StrUtil.sub(bodyStr, 0, 1000));

                    // 重新构建完整的响应
                    return Mono.just(ClientResponse.create(response.statusCode())
                        .headers(headers -> headers.addAll(response.headers().asHttpHeaders()))
                        .body(Flux.just(DefaultDataBufferFactory.sharedInstance.wrap(bodyBytes)))
                        .build());
                });
        });
    };
}
