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

/**
 * After a YouTubeChannels document is created or updated,
 * automatically download the channel profile image if the branding.logo field is empty
 * and a channelThumbnailUrl is available.
 */
export const downloadChannelImage: CollectionAfterChangeHook = async ({ doc, req }) => {
  // Skip if logo already exists
  if (doc.branding?.logo) return doc

  // Need channelThumbnailUrl (set from YouTube API or manually)
  const thumbnailUrl = doc.channelThumbnailUrl
  if (!thumbnailUrl) return doc

  const channelId = doc.youtubeChannelId
  if (!channelId) return doc

  const filename = `yt-channel-${channelId}.jpg`
  const tenantId = typeof doc.tenant === 'object' ? doc.tenant?.id : doc.tenant

  const mediaId = await downloadAndUploadImage(req.payload, {
    url: thumbnailUrl,
    filename,
    alt: doc.name ? `Kanal: ${typeof doc.name === 'string' ? doc.name : doc.name?.de || channelId}` : `YouTube Channel ${channelId}`,
    tenantId: tenantId || undefined,
  })

  if (mediaId) {
    await req.payload.update({
      collection: 'youtube-channels',
      id: doc.id,
      data: { branding: { ...(doc.branding || {}), logo: mediaId } },
      depth: 0,
    })
    console.log(`[yt-thumbnail] Auto-downloaded channel image for ${channelId} (media: ${mediaId})`)
  }

  return doc
}
