import type { Context } from 'hono'
import { previewPrune, runPrune } from '../store/prune.ts'

export async function handlePrune(c: Context): Promise<Response> {
  const cutoffRaw = c.req.query('cutoff')
  const cutoff = cutoffRaw ? Number(cutoffRaw) : Number.NaN
  if (!Number.isFinite(cutoff) || cutoff <= 0) {
    return c.json({ error: 'cutoff must be a positive ms epoch' }, 400)
  }

  const isDryRun =
    c.req.method === 'GET' || c.req.query('dry') === '1'

  if (isDryRun) {
    const preview = await previewPrune(cutoff)
    return c.json(preview)
  }

  const vacuum = process.env.THOMAS_PRUNE_VACUUM === '1'
  const result = await runPrune(cutoff, { vacuum })
  return c.json(result)
}
