defmodule Microwaveprop.Workers.UserHomeQthLookupWorkerTest do
  use Microwaveprop.DataCase, async: false
  use Oban.Testing, repo: Microwaveprop.Repo

  import Microwaveprop.AccountsFixtures

  alias Microwaveprop.Repo
  alias Microwaveprop.Workers.UserHomeQthLookupWorker

  # The test config disables enqueueing on registration globally so the
  # rest of the suite doesn't need a Mox stub. We don't toggle that here
  # — these tests invoke the worker directly via `perform_job/2`, which
  # is independent of the enqueue flag.

  describe "perform/1" do
    test "no-ops when the user already has a home_grid set" do
      user =
        user_fixture()
        |> Ecto.Changeset.change(home_grid: "EM13qc", home_lat: 33.1, home_lon: -96.6)
        |> Repo.update!()

      assert :ok = perform_job(UserHomeQthLookupWorker, %{user_id: user.id})
      reloaded = Repo.reload(user)
      assert reloaded.home_grid == "EM13qc"
    end

    test "no-ops when the user no longer exists" do
      assert :ok = perform_job(UserHomeQthLookupWorker, %{user_id: Ecto.UUID.generate()})
    end

    test "populates home QTH from a successful CallsignClient lookup" do
      user = user_fixture()

      # Stub QRZ.com HTTP layer to return coords for the user's callsign.
      # The callsign-location pipeline reads either lat/lon or grid from
      # the QRZ XML; we serve coords directly so the geocoder fallback
      # isn't exercised.
      Req.Test.stub(Microwaveprop.Qrz.Client, fn conn ->
        Plug.Conn.send_resp(conn, 200, """
        <?xml version="1.0" encoding="utf-8"?>
        <QRZDatabase>
          <Session><Key>test-session</Key></Session>
          <Callsign>
            <call>#{user.callsign}</call>
            <lat>33.10</lat>
            <lon>-96.625</lon>
            <grid>EM13qc</grid>
          </Callsign>
        </QRZDatabase>
        """)
      end)

      assert :ok = perform_job(UserHomeQthLookupWorker, %{user_id: user.id})

      reloaded = Repo.reload(user)
      assert is_binary(reloaded.home_grid)
      assert String.starts_with?(reloaded.home_grid, "EM13qc")
      assert is_float(reloaded.home_lat)
      assert is_float(reloaded.home_lon)
    end
  end
end
