/**
 * Proposal expiry reminder cron — proposal-expiry-deadline (wave-12).
 *
 * POST /api/cron/proposal-expiry-reminder
 *
 * Guarded by CRON_SECRET (timing-safe comparison).
 * Schedule: `0 8 * * *` (daily at 08:00 UTC).
 *
 * Notifies OWNER/ADMIN staff 3 days before a proposal expires.
 * Dedup: proposals already reminded in the last 3 days are skipped.
 */
import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import { createDb } from '@zync/db/queries'
import {
  findExpiringProposals,
  getOwnerAdminUserIds,
  insertProposalExpiringNotification,
} from '@zync/db/queries'
import type { AppEnv } from '../../types'

export const proposalExpiryReminderCron = new Hono<AppEnv>()

proposalExpiryReminderCron.post('/', async (c) => {
  // ── CRON_SECRET guard ──────────────────────────────────────────────────────
  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 expiring = await findExpiringProposals(db)

  let notificationsInserted = 0
  let errors = 0

  for (const row of expiring) {
    try {
      const now = new Date()
      const diffMs = row.expiresAt.getTime() - now.getTime()
      const daysRemaining = Math.ceil(diffMs / (24 * 60 * 60 * 1000))

      const userIds = await getOwnerAdminUserIds(db, row.tenantId)

      for (const userId of userIds) {
        await insertProposalExpiringNotification(
          db,
          row.tenantId,
          userId,
          row.id,
          row.title ?? '',
          daysRemaining,
        )
        notificationsInserted++
      }
    } catch (err) {
      errors++
      console.error(`[proposalExpiryReminderCron] error for proposal ${row.id}:`, err)
    }
  }

  console.log(
    `[proposalExpiryReminderCron] reminded=${expiring.length} notifications=${notificationsInserted} errors=${errors}`,
  )
  return c.json({ reminded: expiring.length, notificationsInserted, errors }, 200)
})
