import type { CollectionAfterChangeHook } from 'payload'
import { downloadAndUploadImage } from '../../lib/utils/media-download'
import { getYouTubeThumbnail } from '../../lib/utils/youtube'

/**
 * After a YouTubeContent document is created or updated,
 * automatically download the YouTube thumbnail if the thumbnail field is empty
 * and a YouTube videoId is present.
 */
export const downloadThumbnail: CollectionAfterChangeHook = async ({ doc, req }) => {
  // Skip if thumbnail already exists (manual upload or previous download)
  if (doc.thumbnail) return doc

  // Get the YouTube video ID
  const videoId = doc.youtube?.videoId
  if (!videoId) return doc

  const thumbnailUrl = getYouTubeThumbnail(videoId, 'hq')
  const filename = `yt-thumb-${videoId}.jpg`

  const tenantId = typeof doc.tenant === 'object' ? doc.tenant?.id : doc.tenant

  const mediaId = await downloadAndUploadImage(req.payload, {
    url: thumbnailUrl,
    filename,
    alt: doc.title
      ? `Thumbnail: ${typeof doc.title === 'string' ? doc.title : doc.title?.de || doc.title?.en || videoId}`
      : `YouTube Thumbnail ${videoId}`,
    tenantId: tenantId || undefined,
  })

  if (mediaId) {
    await req.payload.update({
      collection: 'youtube-content',
      id: doc.id,
      data: { thumbnail: mediaId },
      depth: 0,
    })
    console.log(`[yt-thumbnail] Auto-downloaded thumbnail for video ${videoId} (media: ${mediaId})`)
  }

  return doc
}
