package bou.amine.apps.readerforselfossv2.rest

import bou.amine.apps.readerforselfossv2.model.MercuryModel
import bou.amine.apps.readerforselfossv2.model.StatusAndData
import io.github.aakira.napier.Napier
import io.ktor.client.HttpClient
import io.ktor.client.plugins.cache.HttpCache
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json

class MercuryApi {
    var client = createHttpClient()

    private fun createHttpClient(): HttpClient {
        return HttpClient {
            install(HttpCache)
            install(ContentNegotiation) {
                json(
                    Json {
                        prettyPrint = true
                        isLenient = true
                        ignoreUnknownKeys = true
                    },
                )
            }
            install(Logging) {
                logger =
                    object : Logger {
                        override fun log(message: String) {
                            Napier.d(message, tag = "LogMercuryCalls")
                        }
                    }
                level = LogLevel.INFO
            }
            expectSuccess = false
        }
    }

    suspend fun query(url: String): StatusAndData<MercuryModel.ParsedContent> =
        bodyOrFailure(
            client.get("https://amine-bouabdallaoui.fr/parser.php") {
                parameter("link", url)
            },
        )
}