package de.oaa.xxx.app.data.api

import de.oaa.xxx.app.BuildConfig
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiClient {

    private val cookieStore = mutableMapOf<String, MutableList<Cookie>>()

    val cookieJar = object : CookieJar {
        override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
            cookieStore.getOrPut(url.host) { mutableListOf() }.apply {
                removeAll { existing -> cookies.any { it.name == existing.name } }
                addAll(cookies)
            }
        }
        override fun loadForRequest(url: HttpUrl): List<Cookie> =
            cookieStore[url.host] ?: emptyList()
    }

    fun getJwtToken(): String? =
        cookieStore.values.flatten().find { it.name == "jwt" }?.value

    fun setJwtToken(token: String) {
        val host = BuildConfig.BASE_URL.toHttpUrlOrNull()?.host ?: return

        val cookie = Cookie.Builder()
            .name("jwt")
            .value(token)
            .domain(host)
            .path("/")
            .httpOnly()
            .build()

        cookieStore.getOrPut(host) { mutableListOf() }.apply {
            removeAll { it.name == "jwt" }
            add(cookie)
        }
    }

    fun clearCookies() = cookieStore.clear()

    private val okHttpClient = OkHttpClient.Builder()
        .cookieJar(cookieJar)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
        })
        .build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(BuildConfig.BASE_URL + "/")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val authApi: AuthApi = retrofit.create(AuthApi::class.java)
    val aufgabenApi: AufgabenApi = retrofit.create(AufgabenApi::class.java)
    val sessionApi: SessionApi = retrofit.create(SessionApi::class.java)
    val socialApi: SocialApi = retrofit.create(SocialApi::class.java)
    val gruppenApi: GruppenApi = retrofit.create(GruppenApi::class.java)
    val feedApi: FeedApi = retrofit.create(FeedApi::class.java)
}
