// src/app/(payload)/api/cron/youtube-metrics-sync/route.ts
// Syncs video-level performance metrics (views, likes, comments) for all active YouTube channels.

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'

import { VideoMetricsSyncService } from '@/lib/integrations/youtube/VideoMetricsSyncService'
import { requireCronAuth, withCronExecution } from '@/lib/security'

// Monitoring state
let isRunning = false
let lastRunAt: Date | null = null

/**
 * GET /api/cron/youtube-metrics-sync
 * Syncs video performance metrics for all active YouTube channels.
 * Scheduled every 6 hours via Vercel Cron.
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  return withCronExecution(request, { endpoint: 'youtube-metrics-sync' }, async () => {
    if (isRunning) {
      return NextResponse.json(
        { error: 'Video metrics sync already in progress' },
        { status: 423 },
      )
    }

    isRunning = true
    const startedAt = new Date()

    try {
      const payload = await getPayload({ config })
      const service = new VideoMetricsSyncService(payload)

      // Find all active YouTube channels
      const channels = await payload.find({
        collection: 'youtube-channels',
        where: {
          status: { equals: 'active' },
        },
        limit: 0,
        depth: 0,
      })

      console.log(`[Cron] Starting video metrics sync for ${channels.docs.length} channels`)

      let totalSynced = 0
      const errors: string[] = []

      for (const channel of channels.docs) {
        const channelName = (channel as any).name ?? `ID ${channel.id}`

        try {
          const result = await service.syncMetrics(channel.id as number)

          totalSynced += result.syncedCount

          if (result.errors.length > 0) {
            errors.push(`Channel "${channelName}": ${result.errors.join('; ')}`)
          }
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error)
          errors.push(`Channel "${channelName}": ${message}`)
        }
      }

      lastRunAt = startedAt
      const duration = Date.now() - startedAt.getTime()

      console.log(
        `[Cron] Video metrics sync completed: ${totalSynced} videos synced, ${errors.length} errors, ${duration}ms`,
      )

      return NextResponse.json({
        success: errors.length === 0,
        totalSynced,
        channels: channels.docs.length,
        errors,
        duration,
      })
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      console.error('[Cron] youtube-metrics-sync error:', error)

      return NextResponse.json({ error: message }, { status: 500 })
    } finally {
      isRunning = false
    }
  })
}

/**
 * HEAD /api/cron/youtube-metrics-sync
 * Status check for monitoring.
 */
export async function HEAD(request: NextRequest): Promise<NextResponse> {
  const authError = requireCronAuth(request, 'youtube-metrics-sync')
  if (authError) {
    return new NextResponse(null, { status: authError.status })
  }

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

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