// src/app/(payload)/api/cron/youtube-sync/route.ts

import { NextRequest, NextResponse } from 'next/server'
import { runSync, getSyncStatus } from '@/lib/jobs/syncAllComments'
import { requireCronAuth, withCronExecution } from '@/lib/security'

/**
 * GET /api/cron/youtube-sync
 * Wird von externem Cron-Job aufgerufen (z.B. Vercel Cron, cron-job.org)
 */
export async function GET(request: NextRequest) {
  return withCronExecution(request, { endpoint: 'youtube-sync' }, async () => {
    console.log('[Cron] Starting scheduled YouTube sync')

    const result = await runSync()

    if (result.success) {
      const totalNew = result.results?.reduce((sum, r) => sum + r.newComments, 0) || 0
      const totalUpdated = result.results?.reduce((sum, r) => sum + r.updatedComments, 0) || 0

      return NextResponse.json({
        success: true,
        message: `Sync completed: ${totalNew} new, ${totalUpdated} updated comments`,
        results: result.results,
      })
    }

    return NextResponse.json(
      {
        success: false,
        error: result.error,
      },
      { status: 500 },
    )
  })
}

/**
 * HEAD /api/cron/youtube-sync
 * Status-Check für Monitoring
 */
export async function HEAD(request: NextRequest) {
  const authError = requireCronAuth(request, 'youtube-sync')
  if (authError) {
    return new NextResponse(null, { status: authError.status })
  }

  const status = getSyncStatus()

  return new NextResponse(null, {
    status: status.isRunning ? 423 : 200, // 423 = Locked (running)
    headers: {
      'X-Sync-Running': status.isRunning.toString(),
      'X-Last-Run': status.lastRunAt || 'never',
    },
  })
}

export const dynamic = 'force-dynamic'
export const maxDuration = 300 // 5 Minuten max (Vercel)
