defmodule Microwaveprop.Workers.IemreFetchWorker do
  @moduledoc false
  use Oban.Worker, queue: :iemre, max_attempts: 20

  alias Microwaveprop.Weather
  alias Microwaveprop.Weather.IemClient

  require Logger

  @impl Oban.Worker
  def backoff(%Oban.Job{attempt: attempt}) do
    min(120 * Integer.pow(2, attempt - 1), _six_hours = 21_600)
  end

  @impl Oban.Worker
  def perform(%Oban.Job{args: args}) do
    %{"lat" => lat, "lon" => lon, "date" => date_str} = args
    date = Date.from_iso8601!(date_str)

    if Weather.has_iemre_observation?(lat, lon, date) do
      Logger.info("IEMRE observation already exists for #{lat},#{lon} @ #{date_str}")
      :ok
    else
      Logger.info("Fetching IEMRE data for #{lat},#{lon} @ #{date_str}")
      fetch_and_store_iemre(lat, lon, date, date_str)
    end
  end

  defp fetch_and_store_iemre(lat, lon, date, date_str) do
    case IemClient.fetch_iemre(lat, lon, date) do
      {:ok, []} ->
        # Store stub so this lat/lon/date isn't retried on future backfills
        Weather.upsert_iemre_observation(%{lat: lat, lon: lon, date: date, hourly: []})
        Logger.info("IEMRE: no data available for #{lat},#{lon} @ #{date_str}, stored stub")
        :ok

      {:ok, data} ->
        Weather.upsert_iemre_observation(%{
          lat: lat,
          lon: lon,
          date: date,
          hourly: data
        })

        Logger.info("IEMRE observation saved for #{lat},#{lon} @ #{date_str} (#{length(data)} hours)")
        :ok

      {:error, reason} ->
        handle_error(reason, lat, lon, date_str)
    end
  end

  defp handle_error(reason, lat, lon, date_str) do
    if transient_failure?(reason) do
      Logger.error("IEMRE transient error for #{lat},#{lon} @ #{date_str}: #{inspect(reason)}")
      {:error, reason}
    else
      Logger.warning("IEMRE permanent failure for #{lat},#{lon} @ #{date_str}: #{inspect(reason)}")
      {:cancel, reason}
    end
  end

  defp transient_failure?(%{__exception__: true}), do: true
  defp transient_failure?("IEM IEMRE HTTP " <> status), do: server_error?(status)
  defp transient_failure?(_), do: false

  defp server_error?(status) do
    case Integer.parse(status) do
      {code, _} when code in [429, 500, 502, 503, 504] -> true
      _ -> false
    end
  end
end
