package de.tsschulz.tt_tagebuch.shared.api

import de.tsschulz.tt_tagebuch.shared.api.http.AuthedHttpClient
import de.tsschulz.tt_tagebuch.shared.api.models.ApiLogDetailDto
import de.tsschulz.tt_tagebuch.shared.api.models.ApiLogDetailEnvelopeDto
import de.tsschulz.tt_tagebuch.shared.api.models.ApiLogsListEnvelopeDto
import de.tsschulz.tt_tagebuch.shared.api.models.ApiLogsListPageDto
import de.tsschulz.tt_tagebuch.shared.api.models.SchedulerLastExecutionsEnvelopeDto
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.parameter

class ApiLogsApi(
    private val client: AuthedHttpClient,
) {
    suspend fun listLogs(
        limit: Int = 50,
        offset: Int = 0,
        logType: String? = null,
        method: String? = null,
        statusCode: Int? = null,
        pathContains: String? = null,
    ): ApiLogsListPageDto {
        val env = client.http.get("/api/logs") {
            parameter("limit", limit)
            parameter("offset", offset)
            logType?.takeIf { it.isNotBlank() }?.let { parameter("logType", it) }
            method?.takeIf { it.isNotBlank() }?.let { parameter("method", it) }
            statusCode?.let { parameter("statusCode", it) }
            pathContains?.takeIf { it.isNotBlank() }?.let { parameter("path", it) }
        }.body<ApiLogsListEnvelopeDto>()
        return env.data ?: ApiLogsListPageDto()
    }

    suspend fun getLog(id: Int): ApiLogDetailDto? {
        val env = client.http.get("/api/logs/$id").body<ApiLogDetailEnvelopeDto>()
        return env.data
    }

    suspend fun getSchedulerLastExecutions(clubId: Int? = null): SchedulerLastExecutionsEnvelopeDto {
        return client.http.get("/api/logs/scheduler/last-executions") {
            clubId?.let { parameter("clubId", it) }
        }.body()
    }
}
