// src/app/(payload)/api/community/sync-status/route.ts
// Sync Status API für Dashboard

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { getUnifiedSyncStatus } from '@/lib/jobs/UnifiedSyncService'
import { getSyncStatus as getYouTubeSyncStatus } from '@/lib/jobs/syncAllComments'

/**
 * GET /api/community/sync-status
 * Gibt den aktuellen Sync-Status für alle Plattformen zurück
 */
export async function GET(request: NextRequest) {
  try {
    const payload = await getPayload({ config })

    // Authentifizierung prüfen
    const { user } = await payload.auth({ headers: request.headers })

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Sync-Status abrufen
    const unifiedStatus = getUnifiedSyncStatus()
    const youtubeStatus = getYouTubeSyncStatus()

    // Account-Statistiken laden
    const accounts = await payload.find({
      collection: 'social-accounts',
      where: {
        isActive: { equals: true },
      },
      limit: 100,
      depth: 2,
    })

    // Nach Plattform aggregieren
    const platformStats: Record<
      string,
      {
        platform: string
        accountCount: number
        accounts: Array<{
          id: number
          name: string
          lastSyncedAt: string | null
          followers: number
          totalPosts: number
        }>
      }
    > = {}

    for (const account of accounts.docs) {
      const platformDoc = account.platform as { slug?: string; name?: string } | undefined
      const platformSlug = platformDoc?.slug || 'unknown'
      const platformName = platformDoc?.name || platformSlug

      if (!platformStats[platformSlug]) {
        platformStats[platformSlug] = {
          platform: platformName,
          accountCount: 0,
          accounts: [],
        }
      }

      const stats = account.stats as {
        lastSyncedAt?: string
        followers?: number
        totalPosts?: number
      } | undefined

      platformStats[platformSlug].accountCount++
      platformStats[platformSlug].accounts.push({
        id: account.id as number,
        name: (account.displayName as string) || `Account ${account.id}`,
        lastSyncedAt: stats?.lastSyncedAt || null,
        followers: stats?.followers || 0,
        totalPosts: stats?.totalPosts || 0,
      })
    }

    // Interaktions-Statistiken
    const interactionStats = await payload.find({
      collection: 'community-interactions',
      limit: 0, // Nur Count
    })

    // Neue Interaktionen heute
    const todayStart = new Date()
    todayStart.setHours(0, 0, 0, 0)

    const todayInteractions = await payload.find({
      collection: 'community-interactions',
      where: {
        createdAt: { greater_than: todayStart.toISOString() },
      },
      limit: 0,
    })

    // Unbeantwortete Interaktionen
    const unansweredInteractions = await payload.find({
      collection: 'community-interactions',
      where: {
        status: { in: ['new', 'in_review'] },
      },
      limit: 0,
    })

    return NextResponse.json({
      // Live Sync-Status
      syncStatus: {
        isRunning: unifiedStatus.isRunning || youtubeStatus.isRunning,
        currentPlatform: unifiedStatus.currentPlatform,
        currentAccount: unifiedStatus.currentAccount,
        progress: unifiedStatus.progress,
        lastRunAt: unifiedStatus.lastRunAt || youtubeStatus.lastRunAt,
      },

      // Plattform-Übersicht
      platforms: Object.values(platformStats),

      // Interaktions-Statistiken
      interactions: {
        total: interactionStats.totalDocs,
        today: todayInteractions.totalDocs,
        unanswered: unansweredInteractions.totalDocs,
      },

      // Letztes Sync-Ergebnis
      lastSyncResult: unifiedStatus.lastResult
        ? {
            success: unifiedStatus.lastResult.success,
            startedAt: unifiedStatus.lastResult.startedAt,
            completedAt: unifiedStatus.lastResult.completedAt,
            duration: unifiedStatus.lastResult.duration,
            platforms: unifiedStatus.lastResult.platforms,
            totalNewComments: unifiedStatus.lastResult.results.reduce(
              (sum, r) => sum + r.newComments,
              0
            ),
            totalUpdatedComments: unifiedStatus.lastResult.results.reduce(
              (sum, r) => sum + r.updatedComments,
              0
            ),
            totalErrors: unifiedStatus.lastResult.errors.length,
          }
        : null,
    })
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error'
    console.error('[API] sync-status error:', error)
    return NextResponse.json({ error: message }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
