import type { Payload } from 'payload'

interface DownloadOptions {
  url: string
  filename: string
  alt?: string
  tenantId?: number
}

/**
 * Downloads an image from a URL and creates a Payload Media document.
 *
 * - Checks for existing media with same filename first (deduplication)
 * - Returns the Media document ID on success, null on failure
 * - Never throws — errors are logged and null is returned
 */
export async function downloadAndUploadImage(
  payload: Payload,
  options: DownloadOptions,
): Promise<number | null> {
  const { url, filename, alt, tenantId } = options

  try {
    // Check for existing media with same filename
    const existing = await payload.find({
      collection: 'media',
      where: {
        filename: { equals: filename },
        ...(tenantId ? { tenant: { equals: tenantId } } : {}),
      },
      limit: 1,
      depth: 0,
    })

    if (existing.docs[0]) {
      return existing.docs[0].id as number
    }

    // Download the image with timeout
    const controller = new AbortController()
    const timeout = setTimeout(() => controller.abort(), 10_000)

    const response = await fetch(url, { signal: controller.signal })
    clearTimeout(timeout)

    if (!response.ok) {
      console.log(`[media-download] HTTP ${response.status} for ${url}`)
      return null
    }

    const arrayBuffer = await response.arrayBuffer()
    const buffer = Buffer.from(arrayBuffer)
    const contentType = response.headers.get('content-type') || 'image/jpeg'

    // Create Payload Media document
    const media = await payload.create({
      collection: 'media',
      data: {
        alt: alt || filename.replace(/[-_]/g, ' ').replace(/\.\w+$/, ''),
        ...(tenantId ? { tenant: tenantId } : {}),
      },
      file: {
        name: filename,
        data: buffer,
        mimetype: contentType,
        size: buffer.length,
      },
    })

    console.log(`[media-download] Created media ${media.id} from ${url}`)
    return media.id as number
  } catch (error) {
    console.log(`[media-download] Failed to download ${url}:`, (error as Error).message)
    return null
  }
}
