import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
import { processRoundClose } from '@/server/services/round-finalization'

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 })
  }

  try {
    const now = new Date()

    // Find rounds with expired grace periods that haven't been finalized
    const expiredRounds = await prisma.round.findMany({
      where: {
        status: 'ROUND_CLOSED',
        gracePeriodEndsAt: { lt: now },
        finalizedAt: null,
      },
      select: { id: true, name: true },
    })

    const results: Array<{ roundId: string; roundName: string; processed: number }> = []

    for (const round of expiredRounds) {
      try {
        const result = await processRoundClose(round.id, 'system-cron', prisma)
        results.push({ roundId: round.id, roundName: round.name, processed: result.processed })
      } catch (err) {
        console.error(`[Cron] processRoundClose failed for round ${round.id}:`, err)
      }
    }

    return NextResponse.json({
      ok: true,
      processedRounds: results.length,
      results,
      timestamp: now.toISOString(),
    })
  } catch (error) {
    console.error('Cron grace period processing failed:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
