/**
 * Nightly audit log retention cron — tenant-audit-log spec.
 *
 * POST /api/cron/audit-log-retention
 *
 * Guarded by CRON_SECRET (timing-safe comparison via @zync/auth#timingSafeEqual).
 * Purges tenant_audit_log rows past each tier's retention window:
 *   - business:    90 days
 *   - enterprise:  365 days
 *   - freelancer / white_label: no purge (retention window not defined)
 *
 * This is the ONLY DELETE path against tenant_audit_log.
 * Scheduled: 03:00 UTC nightly (wrangler.toml crons, name: audit-log-retention).
 */
import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import { createDb, purgeAuditLogByRetention } from '@zync/db/queries'
import type { AppEnv } from '../../types'

export const auditLogRetentionCronRoute = new Hono<AppEnv>()

auditLogRetentionCronRoute.post('/', async (c) => {
  // Timing-safe secret check — never use ===
  const secret = c.req.header('x-cron-secret') ?? ''
  const expected = c.env.CRON_SECRET
  if (!expected || expected.length < 16) {
    return c.json({ error: 'Server misconfigured' }, 500)
  }

  if (!timingSafeEqual(secret, expected)) {
    return c.json({ error: 'Forbidden' }, 403)
  }

  const db = createDb(c.env)
  const result = await purgeAuditLogByRetention(db)

  return c.json(
    {
      purged: result,
      ok: true,
    },
    200,
  )
})
