package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtAccountEnvelope
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtAccountSaveResponse
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtAccountStatusDto
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtAccountUpsertBody
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtVerifyBody
import de.tsschulz.tt_tagebuch.shared.api.models.ClickTtVerifyResponseDto
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
import kotlinx.serialization.json.JsonObject

class ClickTtAccountApi(
    private val client: AuthedHttpClient,
) {
    suspend fun getAccount(): ClickTtAccountEnvelope =
        client.http.get("/api/clicktt-account/account").body()

    suspend fun getStatus(): ClickTtAccountStatusDto =
        client.http.get("/api/clicktt-account/status").body()

    suspend fun upsertAccount(body: ClickTtAccountUpsertBody): ClickTtAccountSaveResponse =
        client.http.post("/api/clicktt-account/account") {
            contentType(ContentType.Application.Json)
            setBody(body)
        }.body()

    suspend fun verifyLogin(password: String? = null): ClickTtVerifyResponseDto =
        client.http.post("/api/clicktt-account/verify") {
            contentType(ContentType.Application.Json)
            setBody(
                if (password != null) {
                    ClickTtVerifyBody(password = password)
                } else {
                    JsonObject(emptyMap())
                },
            )
        }.body()

    suspend fun deleteAccount() {
        client.http.delete("/api/clicktt-account/account")
    }
}
