// src/lib/integrations/youtube/CommentsSyncService.ts

import type { Payload } from 'payload'
import { YouTubeClient, type CommentThread } from './YouTubeClient'
import { ClaudeAnalysisService } from '../claude/ClaudeAnalysisService'

interface SyncOptions {
  socialAccountId: number
  sinceDate?: Date
  maxComments?: number
  analyzeWithAI?: boolean
}

interface SyncResult {
  success: boolean
  newComments: number
  updatedComments: number
  newReplies: number
  errors: string[]
  syncedAt: Date
}

export class CommentsSyncService {
  private payload: Payload
  private claudeService: ClaudeAnalysisService

  constructor(payload: Payload) {
    this.payload = payload
    this.claudeService = new ClaudeAnalysisService()
  }

  /**
   * Kommentare für einen Social Account synchronisieren
   */
  async syncComments(options: SyncOptions): Promise<SyncResult> {
    const {
      socialAccountId,
      sinceDate,
      maxComments = 100,
      analyzeWithAI = true,
    } = options

    const result: SyncResult = {
      success: false,
      newComments: 0,
      updatedComments: 0,
      newReplies: 0,
      errors: [],
      syncedAt: new Date(),
    }

    try {
      // 1. Social Account laden
      const account = await this.payload.findByID({
        collection: 'social-accounts',
        id: socialAccountId,
        depth: 2,
      })

      if (!account) {
        result.errors.push('Social Account nicht gefunden')
        return result
      }

      // 2. Platform prüfen
      const platform = account.platform as { slug?: string }
      if (platform?.slug !== 'youtube') {
        result.errors.push('Nur YouTube wird derzeit unterstützt')
        return result
      }

      // 3. YouTube Client initialisieren
      const credentials = account.credentials as {
        accessToken?: string
        refreshToken?: string
      }

      if (!credentials?.accessToken || !credentials?.refreshToken) {
        result.errors.push('Keine gültigen API-Credentials')
        return result
      }

      const youtubeClient = new YouTubeClient(
        {
          clientId: process.env.YOUTUBE_CLIENT_ID!,
          clientSecret: process.env.YOUTUBE_CLIENT_SECRET!,
          accessToken: credentials.accessToken,
          refreshToken: credentials.refreshToken,
        },
        this.payload
      )

      // 4. Kommentare abrufen
      const channelId = account.externalId as string
      const comments = await youtubeClient.getChannelComments(
        channelId,
        sinceDate,
        maxComments
      )

      // 5. Kommentare verarbeiten
      for (const comment of comments) {
        try {
          const processResult = await this.processComment(
            comment,
            account,
            analyzeWithAI,
            youtubeClient,
          )
          if (processResult.isNew) {
            result.newComments++
          } else {
            result.updatedComments++
          }
          result.newReplies += processResult.newReplies
        } catch (error) {
          result.errors.push(`Fehler bei Kommentar ${comment.id}: ${error}`)
        }
      }

      // 6. Account-Stats aktualisieren
      await this.payload.update({
        collection: 'social-accounts',
        id: socialAccountId,
        data: {
          stats: {
            lastSyncedAt: new Date().toISOString(),
          },
        },
      })

      result.success = true
    } catch (error) {
      result.errors.push(`Sync-Fehler: ${error}`)
    }

    return result
  }

  /**
   * Einzelnen Kommentar verarbeiten
   */
  private async processComment(
    comment: CommentThread,
    account: any,
    analyzeWithAI: boolean,
    youtubeClient?: YouTubeClient,
  ): Promise<{ isNew: boolean; newReplies: number }> {
    const snippet = comment.snippet.topLevelComment.snippet

    // Prüfen ob Kommentar bereits existiert
    const existing = await this.payload.find({
      collection: 'community-interactions',
      where: {
        externalId: { equals: comment.id },
      },
      limit: 1,
    })

    const isNew = existing.totalDocs === 0

    // AI-Analyse durchführen
    let analysis = null
    if (analyzeWithAI) {
      analysis = await this.claudeService.analyzeComment(snippet.textOriginal)
    }

    // Verknüpften Content finden (falls Video-ID vorhanden)
    let linkedContentId = null
    if (comment.snippet.videoId) {
      const content = await this.payload.find({
        collection: 'youtube-content',
        where: {
          youtubeVideoId: { equals: comment.snippet.videoId },
        },
        limit: 1,
      })
      if (content.docs[0]) {
        linkedContentId = content.docs[0].id
      }
    }

    // Platform-ID holen
    const platform = await this.payload.find({
      collection: 'social-platforms',
      where: {
        slug: { equals: 'youtube' },
      },
      limit: 1,
    })
    const platformId = platform.docs[0]?.id

    const interactionData = {
      platform: platformId,
      socialAccount: account.id,
      linkedContent: linkedContentId,
      type: 'comment' as const,
      externalId: comment.id,
      author: {
        name: snippet.authorDisplayName,
        handle: snippet.authorChannelId?.value,
        profileUrl: snippet.authorChannelUrl,
        avatarUrl: snippet.authorProfileImageUrl,
        isVerified: false,
        isSubscriber: false,
        isMember: false,
      },
      message: snippet.textOriginal,
      messageHtml: snippet.textDisplay,
      publishedAt: new Date(snippet.publishedAt).toISOString(),
      engagement: {
        likes: snippet.likeCount || 0,
        replies: comment.snippet.totalReplyCount || 0,
        isHearted: false,
        isPinned: false,
      },
      ...(analysis && {
        analysis: {
          sentiment: analysis.sentiment,
          sentimentScore: analysis.sentimentScore,
          confidence: analysis.confidence,
          topics: analysis.topics.map((t) => ({ topic: t })),
          language: analysis.language,
          suggestedReply: analysis.suggestedReply,
          analyzedAt: new Date().toISOString(),
        },
        flags: {
          isMedicalQuestion: analysis.isMedicalQuestion,
          requiresEscalation: analysis.requiresEscalation,
          isSpam: analysis.isSpam,
          isFromInfluencer: false,
        },
      }),
      status: 'new' as const,
      priority: 'normal' as const,
    }

    let parentInteractionId: number | null = null

    if (isNew) {
      const created = await this.payload.create({
        collection: 'community-interactions',
        draft: false,
        data: interactionData,
      })
      parentInteractionId = created.id
    } else {
      await this.payload.update({
        collection: 'community-interactions',
        id: existing.docs[0].id,
        data: {
          ...interactionData,
          // Behalte existierende Workflow-Daten
          status: existing.docs[0].status,
          priority: existing.docs[0].priority,
          assignedTo: existing.docs[0].assignedTo,
        },
      })
      parentInteractionId = existing.docs[0].id
    }

    // Reply-Threads synchronisieren
    let newReplies = 0
    if (youtubeClient && comment.snippet.totalReplyCount > 0) {
      newReplies = await this.processReplyThread(
        comment,
        account,
        parentInteractionId,
        platformId,
        linkedContentId,
        youtubeClient,
        analyzeWithAI,
      )
    }

    return { isNew, newReplies }
  }

  /**
   * Antworten eines Kommentar-Threads synchronisieren
   */
  private async processReplyThread(
    comment: CommentThread,
    account: any,
    parentInteractionId: number | null,
    platformId: any,
    linkedContentId: any,
    youtubeClient: YouTubeClient,
    analyzeWithAI: boolean,
  ): Promise<number> {
    let newReplies = 0

    try {
      const { replies } = await youtubeClient.getCommentReplies(
        comment.snippet.topLevelComment.id,
      )

      for (const reply of replies) {
        const replyExists = await this.payload.find({
          collection: 'community-interactions',
          where: {
            externalId: { equals: reply.id },
          },
          limit: 1,
        })

        if (replyExists.totalDocs > 0) {
          continue
        }

        let replyAnalysis = null
        if (analyzeWithAI) {
          replyAnalysis = await this.claudeService.analyzeComment(
            reply.snippet.textOriginal,
          )
        }

        await this.payload.create({
          collection: 'community-interactions',
          draft: false,
          data: {
            platform: platformId,
            socialAccount: account.id,
            linkedContent: linkedContentId,
            type: 'reply' as const,
            externalId: reply.id,
            parentInteraction: parentInteractionId,
            author: {
              name: reply.snippet.authorDisplayName,
              handle: reply.snippet.authorChannelId?.value,
              profileUrl: reply.snippet.authorChannelUrl,
              avatarUrl: reply.snippet.authorProfileImageUrl,
              isVerified: false,
              isSubscriber: false,
              isMember: false,
            },
            message: reply.snippet.textOriginal,
            messageHtml: reply.snippet.textDisplay,
            publishedAt: new Date(reply.snippet.publishedAt).toISOString(),
            engagement: {
              likes: reply.snippet.likeCount || 0,
              replies: 0,
              isHearted: false,
              isPinned: false,
            },
            ...(replyAnalysis && {
              analysis: {
                sentiment: replyAnalysis.sentiment,
                sentimentScore: replyAnalysis.sentimentScore,
                confidence: replyAnalysis.confidence,
                topics: replyAnalysis.topics.map((t) => ({ topic: t })),
                language: replyAnalysis.language,
                suggestedReply: replyAnalysis.suggestedReply,
                analyzedAt: new Date().toISOString(),
              },
              flags: {
                isMedicalQuestion: replyAnalysis.isMedicalQuestion,
                requiresEscalation: replyAnalysis.requiresEscalation,
                isSpam: replyAnalysis.isSpam,
                isFromInfluencer: false,
              },
            }),
            status: 'new' as const,
            priority: 'normal' as const,
          },
        })

        newReplies++
      }
    } catch (error) {
      console.error(
        `Error syncing replies for comment ${comment.id}:`,
        error,
      )
    }

    return newReplies
  }
}

export type { SyncOptions, SyncResult }
