import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { processDigests } from '@/server/services/email-digest'

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 {
    // Determine digest type: check query param, or default based on day of week
    const { searchParams } = new URL(request.url)
    let digestType = searchParams.get('type') as 'daily' | 'weekly' | null

    if (!digestType) {
      const dayOfWeek = new Date().getDay()
      // Monday = 1 → run weekly; all other days → run daily
      digestType = dayOfWeek === 1 ? 'weekly' : 'daily'
    }

    const result = await processDigests(digestType)

    return NextResponse.json({
      ok: true,
      digestType,
      sent: result.sent,
      errors: result.errors,
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Cron digest processing failed:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
