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

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { YouTubeClient } from '@/lib/integrations/youtube/YouTubeClient'

export async function POST(req: NextRequest) {
  try {
    const payload = await getPayload({ config })

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

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

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

    const body = await req.json()
    const { interactionId, replyText, templateId } = body

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

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

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

    // 2. Platform prüfen
    const platform = interaction.platform as { slug?: string }
    if (platform?.slug !== 'youtube') {
      return NextResponse.json(
        { error: 'Nur YouTube wird derzeit unterstützt' },
        { status: 400 }
      )
    }

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

    if (!account?.credentials?.accessToken || !account?.credentials?.refreshToken) {
      return NextResponse.json(
        { error: 'Keine gültigen API-Credentials' },
        { status: 400 }
      )
    }

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

    // 4. Reply senden
    const replyId = await youtubeClient.replyToComment(
      interaction.externalId as string,
      replyText
    )

    // 5. Interaction aktualisieren
    await payload.update({
      collection: 'community-interactions',
      id: interactionId,
      data: {
        status: 'replied',
        response: {
          text: replyText,
          usedTemplate: templateId || null,
          sentAt: new Date().toISOString(),
          sentBy: userWithRoles.id,
          externalReplyId: replyId,
        },
      },
    })

    // 6. Template Usage Counter erhöhen
    if (templateId) {
      const template = await payload.findByID({
        collection: 'community-templates',
        id: templateId,
      })
      if (template) {
        await payload.update({
          collection: 'community-templates',
          id: templateId,
          data: {
            usageCount: ((template as { usageCount?: number }).usageCount || 0) + 1,
          },
        })
      }
    }

    return NextResponse.json({
      success: true,
      replyId,
    })
  } catch (error: unknown) {
    console.error('Reply error:', error)
    const message = error instanceof Error ? error.message : 'Unknown error'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}

export const dynamic = 'force-dynamic'
