defmodule SimpleshopTheme.Products.ProductImageTest do
  use SimpleshopTheme.DataCase, async: false

  alias SimpleshopTheme.Products.ProductImage

  import SimpleshopTheme.ProductsFixtures

  describe "changeset/2" do
    setup do
      product = product_fixture()
      {:ok, product: product}
    end

    test "valid attributes create a valid changeset", %{product: product} do
      attrs = valid_product_image_attrs(%{product_id: product.id})
      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      assert changeset.valid?
    end

    test "requires product_id", %{product: _product} do
      attrs = valid_product_image_attrs() |> Map.delete(:product_id)
      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      refute changeset.valid?
      assert "can't be blank" in errors_on(changeset).product_id
    end

    test "requires src", %{product: product} do
      attrs =
        valid_product_image_attrs(%{product_id: product.id})
        |> Map.delete(:src)

      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      refute changeset.valid?
      assert "can't be blank" in errors_on(changeset).src
    end

    test "defaults position to 0", %{product: product} do
      attrs =
        valid_product_image_attrs(%{product_id: product.id})
        |> Map.delete(:position)

      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      assert changeset.valid?
    end

    test "accepts optional alt text", %{product: product} do
      attrs = valid_product_image_attrs(%{product_id: product.id, alt: "Product image alt text"})
      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      assert changeset.valid?
      assert changeset.changes.alt == "Product image alt text"
    end

    test "allows nil alt text", %{product: product} do
      attrs = valid_product_image_attrs(%{product_id: product.id, alt: nil})
      changeset = ProductImage.changeset(%ProductImage{}, attrs)

      assert changeset.valid?
    end
  end
end
