import type { Context } from 'hono'
import { WarmCache } from '../cache/keep-warm.ts'
import {
  computeThomas,
  type ThomasPeriod,
  type ThomasResult,
} from '../store/thomas-queries.ts'

const VALID_PERIODS = new Set<ThomasPeriod>(['24h', '7d', '30d', 'lifetime'])

// Stale-while-revalidate cache for /api/thomas. See cache/keep-warm.ts
// for the strategy — synchronous on first hit per period, then
// background-refreshed every 30s while the endpoint is in use, with a
// 30-minute idle stop so the daemon doesn't burn CPU overnight.
export const thomasCache = new WarmCache<ThomasPeriod, ThomasResult>('thomas')
for (const period of VALID_PERIODS) {
  thomasCache.register(period, () => computeThomas(period))
}

export async function handleThomas(c: Context): Promise<Response> {
  const periodRaw = c.req.query('period') ?? '24h'
  if (!VALID_PERIODS.has(periodRaw as ThomasPeriod)) {
    return c.json({ error: `invalid period: ${periodRaw}` }, 400)
  }
  const period = periodRaw as ThomasPeriod
  if (c.req.query('nocache') === '1') thomasCache.invalidate(period)
  const result = await thomasCache.get(period)
  return c.json(result)
}
