/**
 * Daily invoice payment reminders cron — invoice-payment-reminders (wave-13).
 *
 * POST /api/cron/invoice-reminders
 *
 * Guarded by CRON_SECRET (timing-safe comparison). Runs daily at 07:00 UTC.
 * Cloudflare cron trigger: 0 7 * * *  (dispatched via dispatchCron in index.ts)
 *
 * For each invoice where next_reminder_at <= now() and reminders_disabled = false:
 *   1. Checks tenant invoice_reminders_enabled.
 *   2. Sends the reminder email via sendInvoiceReminder.
 *   3. Advances next_reminder_at to the next enabled stage (or NULL if done).
 */
import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import {
  createDb,
  selectReminderDueInvoices,
  getTenantReminderSettings,
} from '@zync/db/queries'
import { sendInvoiceReminder } from '../../services/invoice-reminder-send'
import type { AppEnv } from '../../types'

export const invoiceRemindersCronRoute = new Hono<AppEnv>()

invoiceRemindersCronRoute.post('/', async (c) => {
  // Timing-safe secret check
  const secret = c.req.header('x-cron-secret') ?? ''
  const expected = (c.env as unknown as Record<string, string>).CRON_SECRET as string | undefined
  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 dueInvoices = await selectReminderDueInvoices(db)

  let sent = 0
  let skipped = 0
  let errors = 0

  // Cache tenant settings per tenant to avoid repeated DB reads
  const tenantSettingsCache = new Map<string, { enabled: boolean }>()

  for (const invoice of dueInvoices) {
    try {
      // Check tenant-level reminders enabled
      let cached = tenantSettingsCache.get(invoice.tenantId)
      if (!cached) {
        const settings = await getTenantReminderSettings(db, invoice.tenantId)
        cached = { enabled: settings.enabled }
        tenantSettingsCache.set(invoice.tenantId, cached)
      }

      if (!cached.enabled) {
        skipped++
        continue
      }

      const result = await sendInvoiceReminder(db, c.env, invoice)
      if (result.sent) {
        sent++
      } else {
        skipped++
      }
    } catch (err) {
      errors++
      console.error(`[invoice-reminders-cron] error for invoice ${invoice.id}: ${err}`)
    }
  }

  return c.json({ sent, skipped, errors, total: dueInvoices.length }, 200)
})
