defmodule AprsmeWeb.Api.V1.ChangesetJSONTest do
  use ExUnit.Case, async: true

  alias AprsmeWeb.Api.V1.ChangesetJSON

  defp invalid_changeset do
    # Use Devices since it has a straightforward required field.
    %Aprsme.Devices{} |> Aprsme.Devices.changeset(%{}) |> Map.put(:action, :insert)
  end

  describe "render error.json" do
    test "returns validation_error envelope with details" do
      result = ChangesetJSON.render("error.json", %{changeset: invalid_changeset()})
      assert result.error.code == "validation_error"
      assert String.length(result.error.message) > 0
      assert Map.has_key?(result.error.details, :identifier)
    end

    test "details include the failing field" do
      result = ChangesetJSON.render("error.json", %{changeset: invalid_changeset()})
      assert Map.has_key?(result.error.details, :identifier)
      [msg | _] = result.error.details.identifier
      assert String.length(msg) > 0
    end

    test "interpolates values from error opts" do
      # Build a changeset whose error uses interpolation (min: 3).
      types = %{name: :string}
      params = %{name: "a"}

      changeset =
        {%{}, types}
        |> Ecto.Changeset.cast(params, Map.keys(types))
        |> Ecto.Changeset.validate_length(:name, min: 3)

      result = ChangesetJSON.render("error.json", %{changeset: changeset})
      [msg | _] = result.error.details.name
      # %{count} should be substituted with "3"
      refute msg =~ "%{count}"
      assert msg =~ "3"
    end
  end
end
