// src/lib/jobs/syncAllComments.ts

import { getPayload } from 'payload'
import config from '@payload-config'
import { CommentsSyncService } from '../integrations/youtube/CommentsSyncService'
import { JobLogger } from './JobLogger'
import type { SyncResult } from '@/types/youtube'

// Global state für Sync-Status
let isRunning = false
let lastRunAt: Date | null = null
let lastResult: SyncResult[] | null = null

/**
 * Führt Sync für alle aktiven YouTube-Accounts durch
 */
export async function runSync(): Promise<{
  success: boolean
  results?: SyncResult[]
  error?: string
}> {
  if (isRunning) {
    return { success: false, error: 'Sync already running' }
  }

  isRunning = true
  const logger = new JobLogger('youtube-sync')
  const results: SyncResult[] = []

  try {
    logger.info('Starting YouTube comments sync')

    const payload = await getPayload({ config })

    // Finde alle aktiven YouTube-Accounts
    const platformResult = await payload.find({
      collection: 'social-platforms',
      where: { slug: { equals: 'youtube' } },
      limit: 1,
    })

    if (!platformResult.docs[0]) {
      logger.warn('No YouTube platform found in database')
      return { success: true, results: [] }
    }

    const accounts = await payload.find({
      collection: 'social-accounts',
      where: {
        and: [
          { isActive: { equals: true } },
          { platform: { equals: platformResult.docs[0].id } },
        ],
      },
      limit: 100,
      depth: 2,
    })

    logger.info(`Found ${accounts.docs.length} active YouTube accounts`)

    if (accounts.docs.length === 0) {
      return { success: true, results: [] }
    }

    const syncService = new CommentsSyncService(payload)

    // Sync jeden Account
    for (const account of accounts.docs) {
      const startTime = Date.now()
      const accountName = (account.displayName as string) || `Account ${account.id}`

      logger.info(`Syncing account: ${accountName}`)

      const result: SyncResult = {
        accountId: account.id as number,
        accountName,
        videosProcessed: 0,
        newComments: 0,
        updatedComments: 0,
        errors: [],
        duration: 0,
      }

      try {
        // Hole letzten Sync-Zeitpunkt
        const stats = account.stats as { lastSyncedAt?: string } | undefined
        const sinceDate = stats?.lastSyncedAt
          ? new Date(stats.lastSyncedAt)
          : new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) // Default: letzte 7 Tage

        const syncResult = await syncService.syncComments({
          socialAccountId: account.id as number,
          sinceDate,
          maxComments: 500,
          analyzeWithAI: true,
        })

        result.newComments = syncResult.newComments
        result.updatedComments = syncResult.updatedComments
        result.errors = syncResult.errors

        if (!syncResult.success) {
          result.errors.push('Sync completed with errors')
        }

        logger.info(
          `Account ${accountName}: ${syncResult.newComments} new, ${syncResult.updatedComments} updated`
        )
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error'
        result.errors.push(message)
        logger.error(`Failed to sync account ${accountName}`, error)
      }

      result.duration = Date.now() - startTime
      results.push(result)

      // Rate limiting zwischen Accounts
      await sleep(1000)
    }

    // Statistiken berechnen
    const totalNew = results.reduce((sum, r) => sum + r.newComments, 0)
    const totalUpdated = results.reduce((sum, r) => sum + r.updatedComments, 0)
    const totalErrors = results.reduce((sum, r) => sum + r.errors.length, 0)

    logger.summary({
      success: true,
      processed: totalNew + totalUpdated,
      errors: totalErrors,
    })

    lastRunAt = new Date()
    lastResult = results

    return { success: true, results }
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Sync failed', error)
    return { success: false, error: message }
  } finally {
    isRunning = false
  }
}

/**
 * Gibt den aktuellen Sync-Status zurück
 */
export function getSyncStatus(): {
  isRunning: boolean
  lastRunAt: string | null
  lastResult: SyncResult[] | null
} {
  return {
    isRunning,
    lastRunAt: lastRunAt?.toISOString() || null,
    lastResult,
  }
}

/**
 * Setzt den Sync-Status zurück (für Tests)
 */
export function resetSyncStatus(): void {
  isRunning = false
  lastRunAt = null
  lastResult = null
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms))
}
