defmodule Microwaveprop.Workers.HrrrNativeGridWorkerTest do
  use Microwaveprop.DataCase, async: true

  alias Microwaveprop.Radio.Contact
  alias Microwaveprop.Workers.HrrrNativeGridWorker

  defp create_contact(attrs) do
    default = %{
      station1: "W5XD",
      station2: "K5TR",
      qso_timestamp: ~U[2026-03-28 18:00:00Z],
      mode: "CW",
      band: Decimal.new("10000"),
      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(Map.merge(default, attrs))
      |> Repo.insert()

    contact
  end

  describe "points_of_interest_for_hour/1" do
    test "returns snapped distinct (lat, lon) pairs for contacts in the ±30 min window" do
      create_contact(%{pos1: %{"lat" => 32.9, "lon" => -97.0}, qso_timestamp: ~U[2026-03-28 17:45:00Z]})
      create_contact(%{pos1: %{"lat" => 33.0, "lon" => -97.1}, qso_timestamp: ~U[2026-03-28 18:15:00Z]})

      points = HrrrNativeGridWorker.points_of_interest_for_hour(~U[2026-03-28 18:00:00Z])

      assert length(points) == 2
      assert {32.9, -97.0} in points
      assert {33.0, -97.1} in points
    end

    test "excludes contacts outside the window" do
      create_contact(%{qso_timestamp: ~U[2026-03-28 17:00:00Z]})

      points = HrrrNativeGridWorker.points_of_interest_for_hour(~U[2026-03-28 19:00:00Z])
      assert points == []
    end

    test "deduplicates coincident positions" do
      create_contact(%{station1: "A", pos1: %{"lat" => 32.9, "lon" => -97.0}})
      create_contact(%{station1: "B", pos1: %{"lat" => 32.9, "lon" => -97.0}})

      points = HrrrNativeGridWorker.points_of_interest_for_hour(~U[2026-03-28 18:00:00Z])
      assert points == [{32.9, -97.0}]
    end
  end

  describe "perform/1" do
    test "returns :ok without making any HTTP request when no contacts exist for the hour" do
      # No contacts at all → no points → no download
      job =
        HrrrNativeGridWorker.new(%{
          "year" => 2026,
          "month" => 3,
          "day" => 28,
          "hour" => 18
        })

      assert {:ok, %Oban.Job{args: _}} = Oban.insert(job)
    end
  end
end
