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

  alias Microwaveprop.AccountsFixtures
  alias Microwaveprop.Repo
  alias Microwaveprop.Rover
  alias Microwaveprop.RoverPlanning
  alias Microwaveprop.Terrain.ElevationClient
  alias Microwaveprop.Workers.RoverMissionBackfillWorker

  setup do
    Req.Test.stub(ElevationClient, fn conn ->
      params = Plug.Conn.fetch_query_params(conn).query_params
      lat_count = params["latitude"] |> String.split(",") |> length()
      Req.Test.json(conn, %{"elevation" => List.duplicate(200.0, lat_count)})
    end)

    :ok
  end

  describe "perform/1" do
    test "re-runs failed paths" do
      user = AccountsFixtures.user_fixture()
      {:ok, _loc} = Rover.create_location(user, %{lat: 32.0, lon: -97.0, status: :good})

      {:ok, mission} =
        RoverPlanning.create_mission(user, %{
          "name" => "Backfill mission",
          "band_mhz" => 10_000,
          "only_known_good" => true,
          "rover_height_ft" => 8.0,
          "station_height_ft" => 30.0,
          "stations" => %{"0" => %{"input" => "EM12kp", "position" => 0}}
        })

      [path] = RoverPlanning.list_paths(mission)
      assert path.status == :complete

      {:ok, _} =
        path
        |> Ecto.Changeset.change(%{status: :failed, error: "transient", result: nil})
        |> Repo.update()

      assert :ok = RoverMissionBackfillWorker.perform(%Oban.Job{})

      [reloaded] = RoverPlanning.list_paths(mission)
      assert reloaded.status == :complete
    end
  end
end
