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

  alias Microwaveprop.Weather.IemreObservation

  @valid_attrs %{
    lat: 32.875,
    lon: -97.0,
    date: ~D[2026-03-28],
    hourly: [
      %{"hour" => 0, "p01m_mm" => 0.0},
      %{"hour" => 1, "p01m_mm" => 0.5}
    ]
  }

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

    test "requires lat, lon, and date" do
      changeset = IemreObservation.changeset(%IemreObservation{}, %{})

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

    test "hourly is optional" do
      attrs = Map.delete(@valid_attrs, :hourly)
      changeset = IemreObservation.changeset(%IemreObservation{}, attrs)
      assert changeset.valid?
    end

    test "persists to the database" do
      changeset = IemreObservation.changeset(%IemreObservation{}, @valid_attrs)
      assert {:ok, obs} = Repo.insert(changeset)
      assert obs.lat == 32.875
      assert obs.lon == -97.0
      assert obs.date == ~D[2026-03-28]
      assert length(obs.hourly) == 2
    end

    test "enforces unique constraint on lat, lon, date" do
      assert {:ok, _} =
               %IemreObservation{}
               |> IemreObservation.changeset(@valid_attrs)
               |> Repo.insert()

      assert {:error, changeset} =
               %IemreObservation{}
               |> IemreObservation.changeset(@valid_attrs)
               |> Repo.insert()

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