package no.svorka.mcms.core

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

/**
 * Builder for the MCMS list-endpoint query parameters. `query`/`projection`/
 * `sort` join as comma-separated `key=value` strings; `start-time`/`end-time`
 * use the UTC `yyyy-MM-dd HH:mm:ss` format.
 */
data class ApiQuery(
    val query: Map<String, String> = emptyMap(),
    val projection: Map<String, Int> = emptyMap(),
    val sort: Map<String, Int> = emptyMap(),
    val limit: Int? = null,
    val skip: Int? = null,
    val next: String? = null,
    val distinct: String? = null,
    val startTime: Date? = null,
    val endTime: Date? = null,
) {
    fun items(): List<Pair<String, String>> {
        val out = mutableListOf<Pair<String, String>>()
        if (query.isNotEmpty()) out += "query" to query.entries.joinToString(",") { "${it.key}=${it.value}" }
        if (projection.isNotEmpty()) out += "projection" to projection.entries.joinToString(",") { "${it.key}=${it.value}" }
        if (sort.isNotEmpty()) out += "sort" to sort.entries.joinToString(",") { "${it.key}=${it.value}" }
        limit?.let { out += "limit" to it.toString() }
        skip?.let { out += "skip" to it.toString() }
        next?.let { out += "next" to it }
        distinct?.let { out += "distinct" to it }
        startTime?.let { out += "start-time" to timeFormatter.format(it) }
        endTime?.let { out += "end-time" to timeFormatter.format(it) }
        return out
    }

    companion object {
        val EMPTY = ApiQuery()

        private val timeFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).apply {
            timeZone = TimeZone.getTimeZone("UTC")
        }

        fun window(lastHours: Int, limit: Int? = null): ApiQuery =
            ApiQuery(startTime = Date(System.currentTimeMillis() - lastHours * 3_600_000L), limit = limit)
    }
}
