defmodule Microwaveprop.Weather.StationTest do
  use Microwaveprop.DataCase, async: true

  alias Microwaveprop.Weather.Station

  @valid_attrs %{
    station_code: "KDFW",
    station_type: "asos",
    name: "Dallas/Fort Worth International",
    lat: 32.8998,
    lon: -97.0403,
    elevation_m: 171.0,
    state: "TX"
  }

  describe "changeset/2" do
    test "valid attributes" do
      changeset = Station.changeset(%Station{}, @valid_attrs)
      assert changeset.valid?
    end

    test "valid sounding station with wmo_number" do
      attrs = %{
        station_code: "FWD",
        station_type: "sounding",
        wmo_number: 72_249,
        name: "Fort Worth",
        lat: 32.83,
        lon: -97.30
      }

      changeset = Station.changeset(%Station{}, attrs)
      assert changeset.valid?
    end

    test "requires station_code, station_type, name, lat, lon" do
      changeset = Station.changeset(%Station{}, %{})

      assert %{
               station_code: ["can't be blank"],
               station_type: ["can't be blank"],
               name: ["can't be blank"],
               lat: ["can't be blank"],
               lon: ["can't be blank"]
             } = errors_on(changeset)
    end

    test "validates station_type inclusion" do
      changeset = Station.changeset(%Station{}, %{@valid_attrs | station_type: "radar"})
      assert %{station_type: ["is invalid"]} = errors_on(changeset)
    end

    test "persists to the database" do
      changeset = Station.changeset(%Station{}, @valid_attrs)
      assert {:ok, station} = Repo.insert(changeset)
      assert station.station_code == "KDFW"
      assert station.station_type == "asos"
      assert station.lat == 32.8998
      assert station.lon == -97.0403
    end

    test "enforces unique station_code + station_type" do
      changeset = Station.changeset(%Station{}, @valid_attrs)
      assert {:ok, _} = Repo.insert(changeset)

      duplicate = Station.changeset(%Station{}, @valid_attrs)
      assert {:error, changeset} = Repo.insert(duplicate)
      assert %{station_code: ["has already been taken"]} = errors_on(changeset)
    end
  end
end
