package com.example.modifier.http

import com.example.modifier.Global
import com.example.modifier.http.response.ErrorResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.HttpResponseValidator
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.resources.Resources
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json

@OptIn(ExperimentalSerializationApi::class)
val KtorClient = HttpClient(OkHttp) {
    defaultRequest {
        Global.load()
        url(Global.serverUrl.endsWith("/").let {
            if (it) Global.serverUrl else "${Global.serverUrl}/"
        })
    }
    install(HttpTimeout) {
        requestTimeoutMillis = 180000
        connectTimeoutMillis = 180000
        socketTimeoutMillis = 180000
    }
    install(Resources)
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            isLenient = true
            ignoreUnknownKeys = true
            explicitNulls = false
        })
    }
    HttpResponseValidator {
        validateResponse { response ->
            if (response.status.value !in 200..299) {
                val error = response.body<ErrorResponse>()
                throw ClientRequestException(response, error.message ?: "Unknown error")
            }
        }
    }
}