import type { CollectionAfterChangeHook } from 'payload'
import { NotificationService } from '@/lib/jobs/NotificationService'
import type { YoutubeContent } from '@/payload-types'

type YouTubeContentStatus = NonNullable<YoutubeContent['status']>

interface TransitionContext {
  currentStatus: YouTubeContentStatus
  youtubeVideoId?: string | null
  hasAllChecklistsComplete: boolean
}

/**
 * Determines the next status based on current state and conditions
 */
export function getNextStatus(context: TransitionContext): YouTubeContentStatus | null {
  const { currentStatus, youtubeVideoId } = context

  // Upload completed → published
  if (currentStatus === 'upload_scheduled' && youtubeVideoId) {
    return 'published'
  }

  return null
}

/**
 * Checks if a manual transition should be suggested
 */
export function shouldTransitionStatus(
  status: YouTubeContentStatus,
  context: { hasVideoFile?: boolean },
): boolean {
  if (status === 'approved' && context.hasVideoFile) return true
  return false
}

/**
 * Hook: Automatische Status-Übergänge nach Änderungen
 */
export const autoStatusTransitions: CollectionAfterChangeHook = async ({
  doc,
  previousDoc,
  req,
  operation,
}) => {
  if (operation !== 'update') return doc

  const nextStatus = getNextStatus({
    currentStatus: doc.status as YouTubeContentStatus,
    youtubeVideoId: doc.youtube?.videoId,
    hasAllChecklistsComplete: false,
  })

  if (nextStatus && nextStatus !== doc.status) {
    console.log(`[autoStatusTransitions] ${doc.id}: ${doc.status} → ${nextStatus}`)

    await req.payload.update({
      collection: 'youtube-content',
      id: doc.id,
      data: { status: nextStatus },
      depth: 0,
    })

    // Notification
    if (doc.assignedTo) {
      const assignedToId = typeof doc.assignedTo === 'object' ? doc.assignedTo.id : doc.assignedTo
      const notificationService = new NotificationService(req.payload)
      await notificationService.createNotification({
        recipientId: assignedToId,
        type: 'system',
        title: `Video-Status automatisch geändert: ${nextStatus}`,
        link: `/admin/collections/youtube-content/${doc.id}`,
        relatedVideoId: doc.id,
      })
    }
  }

  return doc
}
