// src/app/(payload)/api/community/generate-reply/route.ts

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { ClaudeReplyService } from '@/lib/integrations/claude/ClaudeReplyService'
import type { ReplyContext } from '@/types/youtube'

/**
 * POST /api/community/generate-reply
 * Generiert KI-Antwortvorschläge für Community-Interaktionen
 */
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
      communityRole?: string
    }
    const hasAccess =
      userWithRoles.isSuperAdmin ||
      userWithRoles.communityRole === 'manager' ||
      userWithRoles.communityRole === 'moderator' ||
      userWithRoles.communityRole === 'responder'

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

    const body = await request.json()
    const { interactionId, variants = false } = body

    if (!interactionId) {
      return NextResponse.json(
        { error: 'interactionId is required' },
        { status: 400 }
      )
    }

    // Hole Interaction mit Relations
    const interaction = await payload.findByID({
      collection: 'community-interactions',
      id: interactionId,
      depth: 2,
    })

    if (!interaction) {
      return NextResponse.json(
        { error: 'Interaction not found' },
        { status: 404 }
      )
    }

    // Bestimme Channel-Typ basierend auf Account
    const socialAccount = interaction.socialAccount as {
      displayName?: string
      id?: number
    } | null
    const channelType = determineChannelType(socialAccount)

    // Linked Content
    const linkedContent = interaction.linkedContent as {
      title?: string
      topics?: Array<{ topic: string }>
    } | null

    // Analysis
    const analysis = interaction.analysis as {
      sentiment?: string
      topics?: Array<{ topic: string }>
    } | null

    // Flags
    const flags = interaction.flags as {
      isMedicalQuestion?: boolean
    } | null

    // Author
    const author = interaction.author as {
      name?: string
    } | null

    // Baue Kontext
    const context: ReplyContext = {
      channelName: socialAccount?.displayName || 'YouTube Channel',
      channelType,
      videoTitle: linkedContent?.title || 'Video',
      videoTopics: linkedContent?.topics?.map((t) => t.topic) || [],
      commentText: interaction.message as string,
      commentSentiment: analysis?.sentiment || 'neutral',
      authorName: author?.name || 'User',
      isMedicalQuestion: flags?.isMedicalQuestion || false,
    }

    const replyService = new ClaudeReplyService()

    if (variants) {
      // Generiere mehrere Varianten
      const replies = await replyService.generateReplyVariants(context, 3)
      return NextResponse.json({ variants: replies })
    } else {
      // Einzelne Antwort
      const reply = await replyService.generateReply(context)
      return NextResponse.json({ reply })
    }
  } catch (error: unknown) {
    console.error('[GenerateReply] Error:', error)
    const message = error instanceof Error ? error.message : 'Failed to generate reply'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}

/**
 * Bestimmt den Channel-Typ basierend auf Account-Name
 */
function determineChannelType(
  account: { displayName?: string } | null
): 'corporate' | 'lifestyle' | 'business' {
  const name = account?.displayName?.toLowerCase() || ''

  if (name.includes('blogwoman') || name.includes('lifestyle')) {
    return 'lifestyle'
  }
  if (name.includes('business') || name.includes('ccs business')) {
    return 'business'
  }
  return 'corporate'
}

export const dynamic = 'force-dynamic'
