defmodule Mix.Tasks.Berrypod.DownloadImages do
  @moduledoc """
  Enqueues download jobs for product images that haven't been processed yet.

  ## Usage

      mix berrypod.download_images

  This task finds all product images with a `src` URL but no linked `image_id`
  and enqueues them for download via the ImageDownloadWorker.

  Use this to backfill existing products after enabling the image download pipeline.
  """

  use Mix.Task

  @shortdoc "Enqueue product image downloads"

  @impl Mix.Task
  def run(_args) do
    Mix.Task.run("app.start")

    alias Berrypod.Products
    alias Berrypod.Sync.ImageDownloadWorker

    pending = Products.list_pending_downloads(limit: 10_000)
    count = length(pending)

    if count == 0 do
      Mix.shell().info("No pending product images to download.")
    else
      Mix.shell().info("Enqueueing #{count} product images for download...")

      Enum.each(pending, fn image ->
        ImageDownloadWorker.enqueue(image.id)
      end)

      Mix.shell().info("Done. Images will be processed by Oban workers.")
    end
  end
end
