// src/app/(payload)/api/community/sync-comments/route.ts

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

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 {
      isSuperAdmin?: boolean
      youtubeRole?: string
      communityRole?: string
    }
    const hasAccess =
      userWithRoles.isSuperAdmin ||
      userWithRoles.youtubeRole === 'manager' ||
      userWithRoles.communityRole === 'manager' ||
      userWithRoles.communityRole === 'moderator'

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

    const body = await req.json()
    const { socialAccountId, sinceDate, maxComments, analyzeWithAI } = body

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

    const syncService = new CommentsSyncService(payload)

    const result = await syncService.syncComments({
      socialAccountId,
      sinceDate: sinceDate ? new Date(sinceDate) : undefined,
      maxComments: maxComments || 100,
      analyzeWithAI: analyzeWithAI ?? true,
    })

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

export const dynamic = 'force-dynamic'
