defmodule Microwaveprop.Qrz.CallsignTest do
  use Microwaveprop.DataCase, async: true

  alias Microwaveprop.Qrz.Callsign

  describe "changeset/2" do
    test "valid changeset with callsign and data" do
      attrs = %{callsign: "W1AW", data: %{"fname" => "Hiram", "name" => "Maxim"}}
      changeset = Callsign.changeset(%Callsign{}, attrs)

      assert changeset.valid?
    end

    test "requires callsign" do
      changeset = Callsign.changeset(%Callsign{}, %{data: %{"fname" => "Test"}})
      assert %{callsign: ["can't be blank"]} = errors_on(changeset)
    end

    test "requires data" do
      changeset = Callsign.changeset(%Callsign{}, %{callsign: "W1AW"})
      assert %{data: ["can't be blank"]} = errors_on(changeset)
    end

    test "uppercases callsign" do
      attrs = %{callsign: "w1aw", data: %{"fname" => "Test"}}
      changeset = Callsign.changeset(%Callsign{}, attrs)

      assert get_change(changeset, :callsign) == "W1AW"
    end

    test "enforces unique callsign constraint" do
      attrs = %{callsign: "W1AW", data: %{"fname" => "Hiram"}}

      {:ok, _} =
        %Callsign{}
        |> Callsign.changeset(attrs)
        |> Repo.insert()

      {:error, changeset} =
        %Callsign{}
        |> Callsign.changeset(attrs)
        |> Repo.insert()

      assert %{callsign: ["has already been taken"]} = errors_on(changeset)
    end
  end
end
