// 定义请求 & 响应拦截器
package com.example.network

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

/**
 * 请求拦截器：统一加 Header、token 等
 */
val requestInterceptor = Interceptor { chain ->
    val original = chain.request()
    val token = "your_token" // 这里换成你自己的 token
    val newRequest = original.newBuilder()
        .addHeader("Accept", "application/json")
        .addHeader("Content-Type", "application/json")
        // 这里加你自己的 token，如果没有就注释掉
        .addHeader("Authorization", "Bearer $token")
        .build()

    chain.proceed(newRequest)
}

/**
 * 响应拦截器：统一打印日志、做一些简单的错误处理
 */
val responseInterceptor = Interceptor { chain ->
    val request = chain.request()
    val startNs = System.nanoTime()
    val response: Response = chain.proceed(request)
    val tookMs = (System.nanoTime() - startNs) / 1_000_000

    val rawBody = response.body
    val mediaType = rawBody?.contentType()
    val bodyString = rawBody?.string() ?: ""

    Log.d(
        "HTTP",
        "⬇⬇⬇\n" +
                "URL   : ${request.url}\n" +
                "Method: ${request.method}\n" +
                "Code  : ${response.code}\n" +
                "Time  : ${tookMs}ms\n" +
                "Body  : $bodyString\n" +
                "⬆⬆⬆"
    )

    // body 只能读一次，这里读完后再重新构建一个
    response.newBuilder()
        .body(bodyString.toResponseBody(mediaType))
        .build()
}
