package de.tsschulz.tt_tagebuch.shared.api.http

import de.tsschulz.tt_tagebuch.shared.api.ApiConfig
import io.ktor.client.HttpClient
import io.ktor.client.plugins.DefaultRequest
import io.ktor.client.plugins.HttpResponseValidator
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.url
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json

/**
 * HTTP-Client ohne Auth-Header – für Login, Registrierung, Passwort-Reset.
 * 401 löst **keinen** globalen Logout aus (nur [ApiException]).
 */
class PublicHttpClient(
    apiConfig: ApiConfig,
    httpClientEngineFactory: HttpClientEngineFactory,
) {
    val http: HttpClient = HttpClient(httpClientEngineFactory.create()) {
        install(ContentNegotiation) {
            json(
                Json {
                    ignoreUnknownKeys = true
                },
            )
        }
        install(HttpTimeout) {
            requestTimeoutMillis = 60_000
            connectTimeoutMillis = 15_000
            socketTimeoutMillis = 60_000
        }
        HttpResponseValidator {
            validateResponse { response ->
                val statusCode = response.status.value
                if (statusCode >= 400) {
                    val detail = response.userFacingErrorOr("API Fehler $statusCode")
                    throw ApiException(statusCode, detail)
                }
            }
        }
        install(DefaultRequest) {
            url(apiConfig.baseUrl)
            contentType(ContentType.Application.Json)
        }
    }
}
