defmodule BerrypodWeb.ImageControllerTest do
  use BerrypodWeb.ConnCase

  alias Berrypod.Media

  @svg_content ~s(<svg xmlns="http://www.w3.org/2000/svg"><circle fill="#000000" r="10"/></svg>)
  @sample_jpeg File.read!("test/fixtures/sample_1200x800.jpg")

  describe "recolored_svg/2" do
    test "returns 404 for non-existent image", %{conn: conn} do
      conn = get(conn, ~p"/images/#{Ecto.UUID.generate()}/recolored/ff6600")
      assert response(conn, 404) =~ "Image not found"
    end

    test "returns 400 for non-SVG image", %{conn: conn} do
      {:ok, image} =
        Media.upload_image(%{
          image_type: "logo",
          filename: "test.jpg",
          content_type: "image/jpeg",
          file_size: byte_size(@sample_jpeg),
          data: @sample_jpeg
        })

      conn = get(conn, ~p"/images/#{image.id}/recolored/ff6600")
      assert response(conn, 400) =~ "not an SVG"
    end

    test "returns 400 for invalid color", %{conn: conn} do
      {:ok, image} =
        Media.upload_image(%{
          image_type: "logo",
          filename: "test.svg",
          content_type: "image/svg+xml",
          file_size: byte_size(@svg_content),
          data: @svg_content
        })

      conn = get(conn, ~p"/images/#{image.id}/recolored/invalid")
      assert response(conn, 400) =~ "Invalid color"
    end

    test "recolors SVG with valid hex color", %{conn: conn} do
      {:ok, image} =
        Media.upload_image(%{
          image_type: "logo",
          filename: "test.svg",
          content_type: "image/svg+xml",
          file_size: byte_size(@svg_content),
          data: @svg_content
        })

      conn = get(conn, ~p"/images/#{image.id}/recolored/ff6600")

      assert response(conn, 200) =~ ~s(fill="#ff6600")
      assert get_resp_header(conn, "content-type") == ["image/svg+xml; charset=utf-8"]
      assert get_resp_header(conn, "cache-control") == ["public, max-age=3600"]
    end

    test "handles color with leading hash", %{conn: conn} do
      {:ok, image} =
        Media.upload_image(%{
          image_type: "logo",
          filename: "test.svg",
          content_type: "image/svg+xml",
          file_size: byte_size(@svg_content),
          data: @svg_content
        })

      # URL encodes # as %23
      conn = get(conn, "/images/#{image.id}/recolored/%23ff6600")

      assert response(conn, 200) =~ ~s(fill="#ff6600")
    end
  end
end
