/**
 * Recurring invoice generator — manual HTTP trigger (recurring-invoices, P061).
 *
 * POST /api/cron/recurring-invoice-generator — CRON_SECRET-gated (timing-safe).
 *
 * Daily scheduling is owned by RecurringInvoiceAlarmDO (self-rescheduling 06:00
 * UTC alarm), NOT a Cloudflare cron-trigger — the account is at the 5-cron cap, so
 * [triggers] crons stays disabled. This route is the manual/on-demand entry point;
 * both it and the DO call the single shared loop runRecurringInvoiceGeneration().
 */
import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import { createDb } from '@zync/db/queries'
import { runRecurringInvoiceGeneration } from '../../cron/recurring-invoice-generation'
import type { AppEnv } from '../../types'

export const recurringInvoiceGeneratorCron = new Hono<AppEnv>()

recurringInvoiceGeneratorCron.post('/', async (c) => {
  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: 'Unauthorized' }, 401)
  }

  const db = createDb(c.env)
  const today = new Date().toISOString().slice(0, 10)

  const summary = await runRecurringInvoiceGeneration(db, today)

  return c.json({
    ok: true,
    today,
    ...summary,
  })
})
