defmodule Microwaveprop.Workers.SpaceWeatherFetchWorker do
  @moduledoc """
  Polls NOAA SWPC's free public JSON services for the three space-weather
  products we use for HF / Es scoring:

  - Planetary K-index (1-min cadence) — geomagnetic disturbance level
  - 10.7 cm solar flux (hourly) — SSN proxy for HF MUF prediction
  - GOES X-ray flux (1-min, 0.1-0.8nm band) — short-wave fade from flares

  Runs on a 5-minute cron. SWPC publishes Kp and X-ray at 1-min cadence;
  5 minutes strikes a balance between freshness and request volume. Each
  fetch is independent: a failure in one product doesn't block the others.
  """

  use Oban.Worker,
    queue: :space_weather,
    max_attempts: 3,
    unique: [period: 120, states: [:available, :scheduled, :executing, :retryable]]

  alias Microwaveprop.SpaceWeather
  alias Microwaveprop.SpaceWeather.SwpcClient

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    fetch_and_upsert(:kp, &SwpcClient.fetch_kp/0, &SpaceWeather.upsert_kp/1)
    fetch_and_upsert(:f107, &SwpcClient.fetch_f107/0, &SpaceWeather.upsert_solar_flux/1)
    fetch_and_upsert(:xrays, &SwpcClient.fetch_xrays/0, &SpaceWeather.upsert_xray/1)
    :ok
  end

  defp fetch_and_upsert(name, fetcher, upserter) do
    case fetcher.() do
      {:ok, rows} ->
        {:ok, count} = upserter.(rows)
        Logger.info("SpaceWeatherFetch: #{name} upserted #{count} rows")

      {:error, reason} ->
        Logger.warning("SpaceWeatherFetch: #{name} failed: #{inspect(reason)}")
    end
  end
end
