package shop.alien.config.feign;

import feign.Logger;
import feign.Request;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

/**
 * 实现 Feign 日志拦截器
 *
 * @author ssk
 * @version 1.0
 * @date 2025/3/19 9:51
 */
@Slf4j
public class FeignBodyLogger extends Logger {

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        // 可选：打印请求日志
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        // 打印状态码和头信息
        log.info("状态码: {}", response.status());
        log.info("响应头: {}", response.headers());
        if (!isGzipResponse(response)) {
            // 读取并打印响应体（已自动解压）
            if (response.body() != null && !(response.status() == 204 || response.status() == 205)) {
                byte[] bodyData = Util.toByteArray(response.body().asInputStream());
                String body = new String(bodyData, StandardCharsets.UTF_8);
                log.info("响应体: {}", body);
                // 重建响应对象避免流关闭
                return response.toBuilder().body(bodyData).build();
            }
        }
        return response;
    }

    @Override
    protected void log(String configKey, String format, Object... args) {
        // 默认日志输出（可选）
    }

    /**
     * 判断是否为 GZip 压缩响应
     *
     * @param response 请求内容
     * @return 是否为 GZip 压缩响应
     */
    private boolean isGzipResponse(Response response) {
        Collection<String> strings = response.headers().get("Content-Encoding");
        if (null == strings) {
            return false;
        }
        return response.headers().get("Content-Encoding").stream().anyMatch(enc -> enc.contains("gzip"));
    }
}