package com.example.ops_android.data.remote

import com.example.ops_android.data.local.SessionManager
import com.google.gson.JsonParser
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody

class AuthInterceptor(
    private val sessionManager: SessionManager
) : Interceptor {

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

        if (!response.isSuccessful || request.method != "POST") {
            return response
        }

        val contentType = response.header("Content-Type") ?: ""
        if (!contentType.contains("json")) {
            return response
        }

        val body = response.body ?: return response
        val bodyString = body.string()

        try {
            val errCode = JsonParser.parseString(bodyString).asJsonObject.get("err_code")?.asInt ?: 0
            if (errCode == -44) {
                sessionManager.clearCookieCache()
            }
        } catch (_: Exception) {}

        val newBody = bodyString.toResponseBody("application/json".toMediaTypeOrNull())
        return response.newBuilder().body(newBody).build()
    }
}
