package com.rc.httpcore.interceptor

import android.annotation.SuppressLint
import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import org.json.JSONObject
import java.io.IOException

class ParameterValidationInterceptor : Interceptor {
    companion object {
        private const val TAG = "ParameterValidationInterceptor"
    }
    @SuppressLint("LongLogTag")
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        // 检查查询参数
        val originalUrl = request.url()
        Log.d(TAG, "Request parameters: $originalUrl")
        // 创建一个新的请求体，便于后续使用
        val requestBody = request.body()
        val buffer = Buffer()
        requestBody?.writeTo(buffer)

        // 获取请求体的字符串形式（假设为 JSON）
        val requestBodyString = buffer.readUtf8()

        // 建立一个标志来跟踪是否有空参数
        val hasEmptyParameter = StringBuilder()
        val queryParametersLog = StringBuilder()
        val bodyParametersLog = StringBuilder()

        // 检查请求体（例如，POST 请求）
        if (request.method() == "POST" && requestBody != null) {
            try {
                val jsonParams = JSONObject(requestBodyString)
                jsonParams.keys().forEach { key ->
                    val value = jsonParams.optString(key)
                    if (value.isEmpty()) {
                        hasEmptyParameter.append("Body parameter '$key' is empty; ")
                    } else {
                        bodyParametersLog.append("Body parameter '$key': $value; ")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "Failed to parse request body as JSON: ${e.message}")
            }
        }

        if (originalUrl.queryParameterNames().isNotEmpty()) {
            for (name in originalUrl.queryParameterNames()) {
                val value = originalUrl.queryParameter(name)
                if (value.isNullOrEmpty()) {
                    hasEmptyParameter.append("Query parameter '$name' is empty; ")
                } else {
                    queryParametersLog.append("Query parameter '$name': $value; ")
                }
            }
        }

        // 打印所有请求参数（合并为一行）
        Log.d(TAG, "Request parameters: ${queryParametersLog.toString()}${bodyParametersLog.toString()}")


        // 打印空参数信息
        if (hasEmptyParameter.isNotEmpty()) {
            Log.e(TAG, "Request contains empty parameters: $hasEmptyParameter")
        }

        // 继续处理请求
        val response = chain.proceed(request)

        // 读取响应体
        val responseBody = response.body()
        val responseBodyString = responseBody?.string() ?: ""

        // 打印返回值日志
        Log.d(TAG, "Response: $responseBodyString")

        // 创建一个新的响应体，以便返回
        return response.newBuilder()
            .body(ResponseBody.create(responseBody?.contentType(), responseBodyString))
            .build()
    }


}