defmodule Microwaveprop.Workers.StationElevationWorkerTest do
  use Microwaveprop.DataCase, async: false

  import Microwaveprop.AccountsFixtures

  alias Microwaveprop.Rover
  alias Microwaveprop.Rover.FixedStation
  alias Microwaveprop.Workers.StationElevationWorker

  setup do
    tmp = Path.join(System.tmp_dir!(), "station_elev_#{System.unique_integer([:positive])}")
    File.mkdir_p!(tmp)
    prev = Application.get_env(:microwaveprop, :srtm_tiles_dir)
    Application.put_env(:microwaveprop, :srtm_tiles_dir, tmp)

    on_exit(fn ->
      File.rm_rf!(tmp)

      if prev do
        Application.put_env(:microwaveprop, :srtm_tiles_dir, prev)
      else
        Application.delete_env(:microwaveprop, :srtm_tiles_dir)
      end
    end)

    :ok
  end

  describe "perform/1" do
    test "returns :ok and leaves elevation nil when SRTM tile is missing" do
      user = user_fixture()
      {:ok, station} = Rover.create_station(user, %{callsign: "W5LUA", lat: 33.0, lon: -96.0})

      assert :ok = StationElevationWorker.perform(%Oban.Job{args: %{"id" => station.id}})

      reloaded = Repo.get!(FixedStation, station.id)
      assert reloaded.elevation_m == nil
    end

    test "returns :ok when station id no longer exists" do
      assert :ok =
               StationElevationWorker.perform(%Oban.Job{
                 args: %{"id" => Ecto.UUID.generate()}
               })
    end
  end
end
