defmodule SimpleshopTheme.Images.OptimizeWorker do
  @moduledoc """
  Oban worker for processing image variants in the background.
  Handles both database images and filesystem mockups.
  """
  use Oban.Worker, queue: :images, max_attempts: 3

  alias SimpleshopTheme.Images.Optimizer

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"type" => "mockup", "source_path" => source_path}}) do
    output_dir = Path.dirname(source_path)
    basename = Path.basename(source_path, Path.extname(source_path))

    case File.read(source_path) do
      {:ok, data} ->
        case Optimizer.process_file(data, basename, output_dir) do
          {:ok, _} -> :ok
          {:error, reason} -> {:error, reason}
        end

      {:error, reason} ->
        {:error, reason}
    end
  end

  def perform(%Oban.Job{args: %{"image_id" => image_id}}) do
    case Optimizer.process_for_image(image_id) do
      {:ok, _} -> :ok
      {:error, :not_found} -> {:cancel, :image_not_found}
      {:error, :no_data} -> {:cancel, :no_image_data}
      {:error, reason} -> {:error, reason}
    end
  end

  @doc """
  Enqueue a database image for optimization.
  """
  def enqueue(image_id) do
    %{image_id: image_id}
    |> new()
    |> Oban.insert()
  end

  @doc """
  Enqueue a mockup file for variant generation.
  """
  def enqueue_mockup(source_path) when is_binary(source_path) do
    %{type: "mockup", source_path: source_path}
    |> new()
    |> Oban.insert()
  end
end
