defmodule Towerops.Workers.CloudLatencyProbeWorker do
  @moduledoc """
  Oban cron worker that dispatches latency probes from all online cloud agents
  to all cloud-polled devices.

  Runs every 8 hours to collect cross-agent latency data used by
  AgentLatencyEvaluator for automatic device reassignment.

  Each cloud agent receives a list of devices to ping (5 pings per device).
  Results flow back through the existing MonitoringCheck pipeline.
  """
  use Oban.Worker, queue: :maintenance

  alias Towerops.Agents

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    cloud_pollers = Agents.list_online_cloud_pollers()
    devices = Agents.list_cloud_polled_devices()

    if cloud_pollers == [] or devices == [] do
      Logger.info("Cloud latency probe: no work (#{length(cloud_pollers)} pollers, #{length(devices)} devices)")
      :ok
    else
      dispatch_probes(cloud_pollers, devices)
    end
  end

  defp dispatch_probes(cloud_pollers, devices) do
    Logger.info(
      "Cloud latency probe: dispatching to #{length(cloud_pollers)} poller(s) " <>
        "for #{length(devices)} device(s)"
    )

    for poller <- cloud_pollers do
      Phoenix.PubSub.broadcast(
        Towerops.PubSub,
        "agent:#{poller.id}:latency_probe",
        {:latency_probe_jobs, devices}
      )
    end

    :ok
  end
end
