/**
 * YouTube Upload Job Definition
 *
 * Definiert den YouTube-Upload-Job fuer die Queue.
 * Uploads sind ressourcenintensiv, daher nur 2 Retry-Versuche.
 */

import { Job } from 'bullmq'
import { getQueue, QUEUE_NAMES, defaultJobOptions } from '../queue-service'

// Job-Daten Typen
export interface YouTubeUploadJobData {
  contentId: number
  channelId: number
  mediaId: number
  metadata: {
    title: string
    description: string
    tags: string[]
    visibility: 'public' | 'unlisted' | 'private'
    categoryId?: string
  }
  scheduledPublishAt?: string
  triggeredBy: number
}

export interface YouTubeUploadJobResult {
  success: boolean
  youtubeVideoId?: string
  youtubeUrl?: string
  error?: string
  timestamp: string
}

/**
 * Fuegt einen YouTube-Upload-Job zur Queue hinzu
 */
export async function enqueueYouTubeUpload(
  data: YouTubeUploadJobData,
): Promise<Job<YouTubeUploadJobData>> {
  const queue = getQueue(QUEUE_NAMES.YOUTUBE_UPLOAD)

  const jobOptions = {
    ...defaultJobOptions,
    attempts: 2,
  }

  const job = await queue.add('youtube-upload', data, jobOptions)

  console.log(
    `[YouTubeUploadQueue] Job ${job.id} queued for content ${data.contentId} on channel ${data.channelId}`,
  )

  return job
}

/**
 * Holt den Status eines YouTube-Upload-Jobs
 */
export async function getYouTubeUploadJobStatus(jobId: string): Promise<{
  state: string
  progress: number
  result?: YouTubeUploadJobResult
  failedReason?: string
} | null> {
  const queue = getQueue(QUEUE_NAMES.YOUTUBE_UPLOAD)

  const job = await queue.getJob(jobId)
  if (!job) return null

  const [state, progress] = await Promise.all([job.getState(), job.progress])

  return {
    state,
    progress: typeof progress === 'number' ? progress : 0,
    result: job.returnvalue as YouTubeUploadJobResult | undefined,
    failedReason: job.failedReason,
  }
}
