defmodule Mix.Tasks.ResetEnrichmentTest do
  use Microwaveprop.DataCase, async: true

  alias Microwaveprop.Radio.Contact
  alias Mix.Tasks.ResetEnrichment

  defp create_queued_qso do
    import Ecto.Query

    default = %{
      station1: "W5XD",
      station2: "K5TR",
      qso_timestamp: ~U[2026-03-28 18:00:00Z],
      mode: "CW",
      band: Decimal.new("1296"),
      grid1: "EM12",
      grid2: "EM00",
      pos1: %{"lat" => 32.9, "lon" => -97.0},
      pos2: %{"lat" => 30.3, "lon" => -97.7},
      distance_km: Decimal.new("295")
    }

    {:ok, contact} =
      %Contact{}
      |> Contact.changeset(default)
      |> Repo.insert()

    # Set all queued flags to true (not in changeset cast)
    Contact
    |> where([q], q.id == ^contact.id)
    |> Repo.update_all(
      set: [weather_status: "queued", hrrr_status: "queued", iemre_status: "queued", terrain_status: "queued"]
    )

    Repo.get!(Contact, contact.id)
  end

  describe "run/1" do
    test "resets weather, hrrr, and iemre status to pending" do
      contact = create_queued_qso()

      assert contact.weather_status == :queued
      assert contact.hrrr_status == :queued
      assert contact.iemre_status == :queued

      ResetEnrichment.run([])

      updated = Repo.get!(Contact, contact.id)
      assert updated.weather_status == :pending
      assert updated.hrrr_status == :pending
      assert updated.iemre_status == :pending
    end

    test "does not reset terrain status" do
      contact = create_queued_qso()

      ResetEnrichment.run([])

      updated = Repo.get!(Contact, contact.id)
      assert updated.terrain_status == :queued
    end

    test "handles empty database" do
      assert :ok = ResetEnrichment.run([])
    end
  end
end
