package com.example.ops_android.data.remote

import com.example.ops_android.data.local.SessionManager
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.RequestBody.Companion.toRequestBody

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

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

        if (originalRequest.method != "POST") {
            return chain.proceed(originalRequest)
        }

        // Skip multipart requests (e.g., file uploads)
        val ct = originalRequest.body?.contentType()?.toString() ?: ""
        if (ct.contains("multipart")) {
            return chain.proceed(originalRequest)
        }

        val cookieValue = sessionManager.cachedCookieValue

        val gson = Gson()

        val oldMap = if (originalRequest.body != null) {
            val buffer = okio.Buffer()
            originalRequest.body!!.writeTo(buffer)
            @Suppress("UNCHECKED_CAST")
            gson.fromJson(buffer.readUtf8(), Map::class.java) as? Map<String, Any> ?: emptyMap()
        } else {
            emptyMap()
        }

        val newBody = mapOf(
            "data" to (oldMap as Any),
            "userCookieValue" to cookieValue
        )

        val newBodyJson = gson.toJson(newBody)
        val contentType = originalRequest.body?.contentType()
        val newRequestBody = newBodyJson.toRequestBody(contentType)

        return chain.proceed(
            originalRequest.newBuilder()
                .method(originalRequest.method, newRequestBody)
                .build()
        )
    }
}
