import { NextResponse, type NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
import { sendLunchRecapEmail } from '@/lib/email'
import { buildRecapPayload } from '@/server/services/lunch-recap'
import { logAudit } from '@/server/utils/audit'

/**
 * Cron: when a lunch event is past its change deadline and admins have
 * left auto-recap on (cronEnabled), send the recap to admins +
 * extraRecipients and stamp recapSentAt. Idempotent.
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  const cronSecret = request.headers.get('x-cron-secret')
  if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  const now = new Date()
  const events = await prisma.lunchEvent.findMany({
    where: {
      enabled: true,
      cronEnabled: true,
      recapSentAt: null,
      eventAt: { not: null },
    },
  })
  let sent = 0
  for (const event of events) {
    try {
      if (!event.eventAt) continue
      const deadline = new Date(
        event.eventAt.getTime() - event.changeCutoffHours * 3_600_000,
      )
      if (now < deadline) continue
      const payload = await buildRecapPayload(prisma, event.programId)
      const adminUsers = await prisma.user.findMany({
        where: {
          role: { in: ['SUPER_ADMIN', 'PROGRAM_ADMIN'] },
          email: { not: '' },
        },
        select: { email: true },
      })
      const recipients = [
        ...adminUsers.map((u) => u.email).filter(Boolean),
        ...event.extraRecipients,
      ]
      try {
        await sendLunchRecapEmail(recipients, payload)
      } catch (e) {
        console.error('[lunch-recap] email send failed', event.id, e)
      }
      await prisma.lunchEvent.update({
        where: { id: event.id },
        data: { recapSentAt: new Date() },
      })
      await logAudit({
        prisma,
        userId: null,
        action: 'LUNCH_RECAP_SENT',
        entityType: 'LunchEvent',
        entityId: event.id,
        detailsJson: { recipientCount: recipients.length, source: 'cron' },
      })
      sent++
    } catch (e) {
      console.error('[lunch-recap] event failed', event.id, e)
    }
  }
  return NextResponse.json({ ok: true, sent, processedEvents: events.length })
}
