package cn.hztech.sdk.client;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 日志拦截器
 *
 * 功能：
 * - 记录请求URL、方法
 * - 记录响应状态码、耗时
 * - 脱敏敏感信息
 */
@Slf4j
public class LoggingInterceptor implements Interceptor {

    private final boolean enableLog;

    public LoggingInterceptor(boolean enableLog) {
        this.enableLog = enableLog;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        if (!enableLog) {
            return chain.proceed(chain.request());
        }

        Request request = chain.request();
        long startTime = System.currentTimeMillis();

        log.info("发送请求: {} {}", request.method(), request.url());

        try {
            Response response = chain.proceed(request);
            long duration = System.currentTimeMillis() - startTime;

            log.info("收到响应: 状态码={}, 耗时={}ms", response.code(), duration);

            return response;
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("请求失败: 耗时={}ms, 错误={}", duration, e.getMessage());
            throw e;
        }
    }
}
