package com.red.circle.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

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


@Component
public class RestTemplateLoggingInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RestTemplateLoggingInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 执行请求并获取响应
        ClientHttpResponse response = execution.execute(request, body);

        logRequest(request,body);
        // 记录响应信息
        logResponse(response);

        return response;
    }

    private void logResponse(ClientHttpResponse response) throws IOException {
        StringBuilder responseDetails = new StringBuilder();
        responseDetails.append("响应详情：\n");
        responseDetails.append("状态码: ").append(response.getStatusCode()).append("\n");
        responseDetails.append("响应头: ").append(response.getHeaders()).append("\n");
        String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
        responseDetails.append("响应体: ").append(responseBody).append("\n");
        logger.info(responseDetails.toString());
    }

    private void logRequest(HttpRequest request, byte[] body) {
        StringBuilder requestDetails = new StringBuilder();
        requestDetails.append("请求详情：\n");
        requestDetails.append("URL: ").append(request.getURI()).append("\n");
        requestDetails.append("请求方法: ").append(request.getMethod()).append("\n");
        requestDetails.append("请求头: ").append(request.getHeaders()).append("\n");
        if (body.length > 0) {
            requestDetails.append("请求体: ").append(new String(body, StandardCharsets.UTF_8)).append("\n");
        }
        logger.info(requestDetails.toString());
    }


}

