defmodule Berrypod.ImageFixtures do
  @moduledoc """
  Shared fixtures for image-related tests.
  """

  alias Berrypod.Repo
  alias Berrypod.Media.Image

  @sample_jpeg File.read!("test/fixtures/sample_1200x800.jpg")

  def sample_jpeg, do: @sample_jpeg

  def image_fixture(attrs \\ %{}) do
    {:ok, webp, w, h} = Berrypod.Images.Optimizer.to_optimized_webp(@sample_jpeg)

    defaults = %{
      image_type: "product",
      filename: "test.jpg",
      content_type: "image/webp",
      file_size: byte_size(webp),
      data: webp,
      source_width: w,
      source_height: h,
      variants_status: "pending",
      is_svg: false
    }

    %Image{}
    |> Image.changeset(Map.merge(defaults, attrs))
    |> Repo.insert!()
  end

  def svg_fixture do
    svg = ~s(<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect/></svg>)

    %Image{}
    |> Image.changeset(%{
      image_type: "logo",
      filename: "logo.svg",
      content_type: "image/svg+xml",
      file_size: byte_size(svg),
      data: svg,
      is_svg: true,
      svg_content: svg,
      variants_status: "pending"
    })
    |> Repo.insert!()
  end

  def cache_path(id, width, format) do
    ext =
      case format do
        :jpg -> "jpg"
        :webp -> "webp"
        :avif -> "avif"
        "thumb" -> "jpg"
        _ -> to_string(format)
      end

    filename =
      case width do
        "thumb" -> "#{id}-thumb.#{ext}"
        _ -> "#{id}-#{width}.#{ext}"
      end

    Path.join(Berrypod.Images.Optimizer.cache_dir(), filename)
  end

  def cleanup_cache do
    cache_dir = Berrypod.Images.Optimizer.cache_dir()
    if File.exists?(cache_dir), do: File.rm_rf!(cache_dir)
  end
end
