defmodule Microwaveprop.Workers.SolarIndexWorker do
  @moduledoc false
  use Oban.Worker,
    queue: :solar,
    max_attempts: 3,
    unique: [period: 300, states: [:available, :scheduled, :executing, :retryable]]

  alias Microwaveprop.Weather
  alias Microwaveprop.Weather.SolarClient

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

    case SolarClient.fetch_solar_indices() do
      {:ok, all_records} ->
        matched = Enum.filter(all_records, fn r -> r.date == target_date end)
        Weather.upsert_solar_indices_batch(matched)

        if matched != [] do
          Phoenix.PubSub.broadcast(
            Microwaveprop.PubSub,
            "contact_enrichment:solar",
            {:solar_ready, date_str}
          )
        end

        :ok

      {:error, reason} ->
        {:error, reason}
    end
  end

  def perform(%Oban.Job{}) do
    since_date = Date.add(Date.utc_today(), -7)

    case SolarClient.fetch_solar_indices() do
      {:ok, all_records} ->
        all_records
        |> SolarClient.filter_since(since_date)
        |> Weather.upsert_solar_indices_batch()

        :ok

      {:error, reason} ->
        {:error, reason}
    end
  end
end
