defmodule SimpleshopTheme.Images.OptimizeWorkerTest do
  use SimpleshopTheme.DataCase, async: false
  use Oban.Testing, repo: SimpleshopTheme.Repo

  alias SimpleshopTheme.Images.OptimizeWorker
  import SimpleshopTheme.ImageFixtures

  setup do
    cleanup_cache()
    on_exit(&cleanup_cache/0)
    :ok
  end

  describe "perform/1" do
    test "processes image and generates variants" do
      image = image_fixture(%{source_width: 1200, source_height: 800})

      assert :ok = perform_job(OptimizeWorker, %{image_id: image.id})

      # Verify pre-generated variants were created (AVIF and WebP only, not JPEG)
      for w <- [400, 800, 1200], fmt <- [:avif, :webp] do
        assert File.exists?(cache_path(image.id, w, fmt))
      end

      # JPEG is generated on-demand, not pre-generated
      refute File.exists?(cache_path(image.id, 400, :jpg))
    end

    test "cancels for missing image" do
      assert {:cancel, :image_not_found} =
               perform_job(OptimizeWorker, %{image_id: Ecto.UUID.generate()})
    end

    test "skips SVG images" do
      image = svg_fixture()
      assert :ok = perform_job(OptimizeWorker, %{image_id: image.id})
    end
  end

  describe "enqueue/1" do
    test "inserts and executes job (inline mode)" do
      image = image_fixture(%{source_width: 1200, source_height: 800})

      # In inline test mode, job executes immediately
      assert {:ok, %Oban.Job{state: "completed"}} = OptimizeWorker.enqueue(image.id)

      # Verify variants were created (job ran inline)
      assert File.exists?(cache_path(image.id, 400, :avif))
    end
  end
end
