// src/app/(payload)/api/community/sync/route.ts

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import {
  runUnifiedSync,
  getUnifiedSyncStatus,
  type SupportedPlatform,
} from '@/lib/jobs/UnifiedSyncService'

/**
 * POST /api/community/sync
 * Manueller Sync-Trigger für alle Plattformen (YouTube, Facebook, Instagram)
 *
 * Optional: ?platforms=youtube,facebook,instagram (komma-separiert)
 */
export async function POST(request: NextRequest) {
  try {
    const payload = await getPayload({ config })

    // Auth prüfen
    const { user } = await payload.auth({ headers: request.headers })
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Berechtigungen prüfen
    const userWithRoles = user as {
      isSuperAdmin?: boolean
      youtubeRole?: string
      communityRole?: string
    }
    const hasAccess =
      userWithRoles.isSuperAdmin ||
      userWithRoles.youtubeRole === 'manager' ||
      userWithRoles.communityRole === 'manager'

    if (!hasAccess) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    // Prüfe ob bereits ein Sync läuft
    const status = getUnifiedSyncStatus()
    if (status.isRunning) {
      return NextResponse.json(
        {
          error: 'Sync already in progress',
          status,
        },
        { status: 409 }
      )
    }

    // Optionaler Plattform-Filter aus Body oder Query
    let platforms: SupportedPlatform[] | undefined
    try {
      const body = await request.json()
      if (body.platforms && Array.isArray(body.platforms)) {
        platforms = body.platforms as SupportedPlatform[]
      }
    } catch {
      // Kein JSON Body — alle Plattformen syncen
    }

    console.log(
      `[Sync] Manual unified sync triggered by user ${user.id}`,
      platforms ? `(platforms: ${platforms.join(', ')})` : '(all platforms)'
    )

    const result = await runUnifiedSync({ platforms })

    return NextResponse.json({
      success: result.success,
      duration: result.duration,
      platforms: result.platforms,
      results: result.results,
      errors: result.errors.length > 0 ? result.errors : undefined,
    })
  } catch (error: unknown) {
    console.error('[Sync] Error:', error)
    const message = error instanceof Error ? error.message : 'Unknown error'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}

/**
 * GET /api/community/sync
 * Sync-Status abfragen
 */
export async function GET(request: NextRequest) {
  try {
    const payload = await getPayload({ config })

    // Auth prüfen
    const { user } = await payload.auth({ headers: request.headers })
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const status = getUnifiedSyncStatus()

    return NextResponse.json({
      ...status,
      nextRunAt: calculateNextRun(),
    })
  } catch (error: unknown) {
    console.error('[Sync] Status error:', error)
    const message = error instanceof Error ? error.message : 'Unknown error'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}

/**
 * Berechnet den nächsten geplanten Sync-Zeitpunkt
 * (Basierend auf 15-Minuten-Intervall)
 */
function calculateNextRun(): string {
  const now = new Date()
  const minutes = now.getMinutes()
  const nextInterval = Math.ceil(minutes / 15) * 15

  const next = new Date(now)
  next.setMinutes(nextInterval, 0, 0)

  // Falls wir genau auf einem Intervall sind, nächstes nehmen
  if (next <= now) {
    next.setMinutes(next.getMinutes() + 15)
  }

  return next.toISOString()
}

export const dynamic = 'force-dynamic'
