// src/app/(payload)/api/youtube/upload/route.ts

import { getPayload } from 'payload'
import config from '@payload-config'
import { NextRequest, NextResponse } from 'next/server'
import {
  enqueueYouTubeUpload,
  getYouTubeUploadJobStatus,
} from '@/lib/queue/jobs/youtube-upload-job'

/**
 * POST /api/youtube/upload
 *
 * Erstellt einen YouTube-Upload-Job fuer ein YouTubeContent-Dokument.
 * Erwartet { contentId } im Request-Body.
 */
export async function POST(request: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })

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

    const body = await request.json()
    const { contentId } = body

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

    // YouTubeContent laden
    const content = await payload.findByID({
      collection: 'youtube-content',
      id: contentId,
      depth: 1,
    })

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

    const doc = content as unknown as Record<string, unknown>

    if (!doc.videoFile) {
      return NextResponse.json({ error: 'No video file attached' }, { status: 400 })
    }

    // Felder sicher extrahieren
    const channelRaw = doc.channel
    const channelId = typeof channelRaw === 'object' && channelRaw !== null
      ? (channelRaw as { id: number }).id
      : channelRaw as number

    const videoFileRaw = doc.videoFile
    const mediaId = typeof videoFileRaw === 'object' && videoFileRaw !== null
      ? (videoFileRaw as { id: number }).id
      : videoFileRaw as number

    const youtube = doc.youtube as {
      metadata?: {
        youtubeTitle?: string
        youtubeDescription?: string
        tags?: Array<{ tag?: string }>
        visibility?: 'public' | 'unlisted' | 'private'
      }
    } | undefined

    const tags = (youtube?.metadata?.tags || [])
      .map((t) => t.tag)
      .filter((tag): tag is string => Boolean(tag))

    // Upload-Job erstellen
    const job = await enqueueYouTubeUpload({
      contentId: contentId as number,
      channelId,
      mediaId,
      metadata: {
        title: youtube?.metadata?.youtubeTitle || (doc.title as string) || 'Untitled',
        description: youtube?.metadata?.youtubeDescription || (doc.description as string) || '',
        tags,
        visibility: youtube?.metadata?.visibility || 'private',
      },
      scheduledPublishAt: (doc.scheduledPublishDate as string) || undefined,
      triggeredBy: user.id as number,
    })

    // Status auf upload_scheduled setzen
    await payload.update({
      collection: 'youtube-content',
      id: contentId,
      data: { status: 'upload_scheduled' },
    })

    return NextResponse.json({
      success: true,
      jobId: job.id,
      message: 'Upload-Job erstellt',
    })
  } catch (error) {
    console.error('[YouTube Upload API] Error:', error)
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}

/**
 * GET /api/youtube/upload?jobId=xxx
 *
 * Gibt den Status eines YouTube-Upload-Jobs zurueck.
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })

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

    const jobId = request.nextUrl.searchParams.get('jobId')
    if (!jobId) {
      return NextResponse.json({ error: 'jobId required' }, { status: 400 })
    }

    const status = await getYouTubeUploadJobStatus(jobId)
    if (!status) {
      return NextResponse.json({ error: 'Job not found' }, { status: 404 })
    }

    return NextResponse.json(status)
  } catch (error) {
    console.error('[YouTube Upload API] Status check error:', error)
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}
