// src/app/(payload)/api/cron/youtube-channel-sync/route.ts
// Syncs channel-level statistics (subscribers, views, video count) for all active YouTube channels.

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

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

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

/**
 * GET /api/cron/youtube-channel-sync
 * Syncs channel-level metrics for all active YouTube channels.
 * Scheduled daily at 04:00 UTC via Vercel Cron.
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  return withCronExecution(request, { endpoint: 'youtube-channel-sync' }, async () => {
    if (isRunning) {
      return NextResponse.json(
        { error: 'Channel metrics sync already in progress' },
        { status: 423 },
      )
    }

    isRunning = true
    const startedAt = new Date()

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

      console.log('[Cron] Starting channel metrics sync')

      const result = await service.syncAllChannels()

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

      console.log(
        `[Cron] Channel metrics sync completed: ${result.channelsSynced} channels synced, ${result.errors.length} errors, ${duration}ms`,
      )

      return NextResponse.json({
        success: result.success,
        channelsSynced: result.channelsSynced,
        errors: result.errors,
        duration,
      })
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      console.error('[Cron] youtube-channel-sync error:', error)

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

/**
 * HEAD /api/cron/youtube-channel-sync
 * Status check for monitoring.
 */
export async function HEAD(request: NextRequest): Promise<NextResponse> {
  const authError = requireCronAuth(request, 'youtube-channel-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 = 120 // 2 minutes max (Vercel)
