// src/app/(payload)/api/cron/token-refresh/route.ts
// Token Refresh Cron Endpoint

import { NextRequest, NextResponse } from 'next/server'
import {
  runTokenRefresh,
  getTokenRefreshStatus,
  type TokenRefreshOptions,
  type TokenPlatform,
} from '@/lib/jobs/TokenRefreshService'
import { requireCronAuth, withCronExecution } from '@/lib/security'

/**
 * GET /api/cron/token-refresh
 * Prüft und erneuert ablaufende Tokens
 *
 * Query Parameters:
 * - platforms: Komma-separierte Liste (youtube,facebook,instagram)
 * - thresholdDays: Tage vor Ablauf für Refresh (default: 7)
 * - includeExpired: true/false - auch abgelaufene Tokens versuchen
 * - dryRun: true/false - nur prüfen, nicht erneuern
 */
export async function GET(request: NextRequest) {
  return withCronExecution(request, { endpoint: 'token-refresh' }, async () => {
    // Query-Parameter parsen
    const searchParams = request.nextUrl.searchParams
    const options: TokenRefreshOptions = {}

    // Plattform-Filter
    const platformsParam = searchParams.get('platforms')
    if (platformsParam) {
      const platforms = platformsParam.split(',').map((p) => p.trim().toLowerCase())
      const validPlatforms = platforms.filter((p): p is TokenPlatform =>
        ['youtube', 'facebook', 'instagram'].includes(p)
      )
      if (validPlatforms.length > 0) {
        options.platforms = validPlatforms
      }
    }

    // Threshold Days
    const thresholdParam = searchParams.get('thresholdDays')
    if (thresholdParam) {
      const days = parseInt(thresholdParam, 10)
      if (!isNaN(days) && days > 0) {
        options.refreshThresholdDays = days
      }
    }

    // Include Expired
    const includeExpiredParam = searchParams.get('includeExpired')
    if (includeExpiredParam === 'true') {
      options.includeExpired = true
    }

    // Dry Run
    const dryRunParam = searchParams.get('dryRun')
    if (dryRunParam === 'true') {
      options.dryRun = true
    }

    console.log('[Cron] Starting token refresh', { options })

    const result = await runTokenRefresh(options)

    if (result.success) {
      return NextResponse.json({
        success: true,
        message: `Token refresh completed: ${result.stats.refreshed} refreshed, ${result.stats.skipped} skipped`,
        duration: result.duration,
        stats: result.stats,
        notifications: result.notifications.filter((n) => n.type !== 'info'),
      })
    }

    // Teilerfolg oder Fehler
    return NextResponse.json(
      {
        success: false,
        message: `Token refresh completed with issues: ${result.stats.failed} failed, ${result.stats.expired} expired`,
        duration: result.duration,
        stats: result.stats,
        notifications: result.notifications,
        results: result.results.filter((r) => r.action !== 'skipped'),
      },
      { status: result.stats.failed > 0 || result.stats.expired > 0 ? 207 : 200 },
    )
  })
}

/**
 * POST /api/cron/token-refresh
 * Manueller Token-Refresh mit erweiterten Optionen
 */
export async function POST(request: NextRequest) {
  return withCronExecution(request, { endpoint: 'token-refresh' }, async () => {
    try {
      const body = await request.json()
      const options: TokenRefreshOptions = {}

      // Optionen aus Body übernehmen
      if (body.platforms && Array.isArray(body.platforms)) {
        options.platforms = body.platforms.filter((p: string): p is TokenPlatform =>
          ['youtube', 'facebook', 'instagram'].includes(p)
        )
      }

      if (body.accountIds && Array.isArray(body.accountIds)) {
        options.accountIds = body.accountIds.filter(
          (id: unknown) => typeof id === 'number' && id > 0,
        )
      }

      if (typeof body.refreshThresholdDays === 'number' && body.refreshThresholdDays > 0) {
        options.refreshThresholdDays = body.refreshThresholdDays
      }

      if (typeof body.includeExpired === 'boolean') {
        options.includeExpired = body.includeExpired
      }

      if (typeof body.dryRun === 'boolean') {
        options.dryRun = body.dryRun
      }

      console.log('[Cron] Manual token refresh triggered', { options })

      const result = await runTokenRefresh(options)

      return NextResponse.json({
        success: result.success,
        startedAt: result.startedAt,
        completedAt: result.completedAt,
        duration: result.duration,
        stats: result.stats,
        results: result.results,
        notifications: result.notifications,
      })
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Unknown error'
      console.error('[Cron] POST error:', error)
      return NextResponse.json({ error: message }, { status: 500 })
    }
  })
}

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

  const status = getTokenRefreshStatus()

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

export const dynamic = 'force-dynamic'
export const maxDuration = 120 // 2 Minuten max
