/**
 * Featured Video Processing Hook
 *
 * Verarbeitet featuredVideo.embedUrl in Posts:
 * - Extrahiert Video-ID aus URL
 * - Generiert normalisierte Embed-URL mit Privacy-Mode
 */

import type { CollectionBeforeChangeHook } from 'payload'
import { parseVideoUrl, generateEmbedUrl } from '../lib/video'

interface FeaturedVideoData {
  enabled?: boolean
  source?: 'library' | 'embed' | 'upload'
  embedUrl?: string
  video?: number | string
  uploadedVideo?: number | string
  autoplay?: boolean
  muted?: boolean
  replaceImage?: boolean
  // Processed fields (added by this hook)
  processedEmbedUrl?: string
  extractedVideoId?: string
  platform?: string
  thumbnailUrl?: string
}

interface PostDataInput {
  featuredVideo?: FeaturedVideoData
  [key: string]: unknown
}

/**
 * Hook zum Verarbeiten von featuredVideo Embed-URLs
 *
 * - Extrahiert Video-ID und Plattform aus der URL
 * - Generiert normalisierte Embed-URL mit Privacy-Mode (youtube-nocookie)
 * - Speichert Thumbnail-URL für Fallback
 */
export const processFeaturedVideo: CollectionBeforeChangeHook = async ({
  data,
}) => {
  const postData = data as PostDataInput | undefined

  // Nur wenn featuredVideo existiert und aktiviert ist
  if (!postData?.featuredVideo?.enabled) {
    return data
  }

  const featuredVideo = postData.featuredVideo

  // Nur für embed source verarbeiten
  if (featuredVideo.source !== 'embed' || !featuredVideo.embedUrl) {
    return data
  }

  const embedUrl = featuredVideo.embedUrl.trim()

  // URL parsen
  const videoInfo = parseVideoUrl(embedUrl)

  if (!videoInfo || videoInfo.platform === 'unknown') {
    // URL konnte nicht geparst werden - unverändert lassen
    console.warn(`[processFeaturedVideo] Could not parse video URL: ${embedUrl}`)
    return data
  }

  // Video-Metadaten speichern
  featuredVideo.extractedVideoId = videoInfo.videoId || undefined
  featuredVideo.platform = videoInfo.platform
  featuredVideo.thumbnailUrl = videoInfo.thumbnailUrl || undefined

  // Embed-URL mit Privacy-Mode und Playback-Optionen generieren
  const processedUrl = generateEmbedUrl(videoInfo, {
    autoplay: featuredVideo.autoplay ?? false,
    muted: featuredVideo.muted ?? true,
    privacyMode: true, // Immer Privacy-Mode für DSGVO
    showRelated: false, // Keine verwandten Videos
  })

  if (processedUrl) {
    featuredVideo.processedEmbedUrl = processedUrl
  }

  return {
    ...postData,
    featuredVideo,
  }
}
