package com.zaojiao.app.core.http.interceptor

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import javax.inject.Inject

data class JsonResult(
    val status: Int,
    val msg: String?,
)

class ResultInterceptor @Inject constructor(
    private val moshi: Moshi,
) : Interceptor {
    private var resultAdapter: JsonAdapter<JsonResult> =
        moshi.adapter(JsonResult::class.java)

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)

        try {
            val newResponse = response.newBuilder()

            response.body?.apply {
                /* 修改响应中的code值 */
                val body = this.string()
                val result = resultAdapter.fromJson(body)
                result?.run {
                    newResponse.code(status)
                }

                val newBody = body.toResponseBody(
                    contentType = this.contentType()
                )
                newResponse.body(newBody)
            }

            return newResponse.build()
        } catch (e: Throwable) {
            e.printStackTrace()
            val result = JsonResult(
                status = 500,
                msg = e.message,
            )

            val body = resultAdapter.toJson(result).toResponseBody(
                contentType = "application/json".toMediaType()
            )

            return Response.Builder()
                .request(request)
                .protocol(Protocol.HTTP_1_1)
                .code(500)
                .message("Error")
                .body(body)
                .build()
        }
    }
}