/**
 * STATUS_KV cache helpers — system-status-page.
 *
 * Caches the serialized StatusPayload under 'status:current' with a 30-second
 * TTL. Any incident mutation must call invalidateStatusCache() immediately so
 * the next request gets fresh data.
 *
 * Binding: STATUS_KV (KVNamespace) — must be declared in wrangler.toml and Env.
 */
import { createDb } from '@zync/db/queries'
import { getActiveIncidents, deriveServiceStatuses, deriveOverallStatus } from '@zync/db/queries'
import type { Env } from '@zync/types'
import type { StatusPayload } from '@zync/types'

const CACHE_KEY = 'status:current'
const CACHE_TTL_SECONDS = 30

/**
 * Return the current StatusPayload, reading from KV if available, otherwise
 * re-computing from the database and caching the result.
 */
export async function getCachedStatus(env: Env): Promise<StatusPayload> {
  // STATUS_KV is added to the Env interface via the controller (manifest.wrangler)
  const statusKv = (env as Env & { STATUS_KV: KVNamespace }).STATUS_KV
  const cached = await statusKv.get(CACHE_KEY, 'text')
  if (cached) {
    return JSON.parse(cached) as StatusPayload
  }

  const db = createDb(env)
  const activeIncidents = await getActiveIncidents(db)
  const services = deriveServiceStatuses(activeIncidents)
  const overall = deriveOverallStatus(services)

  const payload: StatusPayload = {
    overall,
    services,
    activeIncidents,
    updatedAt: new Date().toISOString(),
  }

  await statusKv.put(CACHE_KEY, JSON.stringify(payload), {
    expirationTtl: CACHE_TTL_SECONDS,
  })

  return payload
}

/**
 * Delete the cached status payload, forcing a recompute on the next request.
 */
export async function invalidateStatusCache(env: Env): Promise<void> {
  const statusKv = (env as Env & { STATUS_KV: KVNamespace }).STATUS_KV
  await statusKv.delete(CACHE_KEY)
}
