defmodule Towerops.JobMonitoring.Events do
  @moduledoc """
  PubSub event broadcasting for job lifecycle events.
  """

  @topic "job:lifecycle"

  @doc """
  Broadcasts a job lifecycle event to PubSub.

  ## Events
  - `:started` - Job began executing
  - `:completed` - Job finished successfully
  - `:failed` - Job failed with error

  ## Metadata
  Optional map with additional context:
  - `duration`: Execution time in seconds
  - `error`: Error message/reason
  - `items_collected`: Number of items discovered/polled
  """
  @spec broadcast_job_event(Oban.Job.t(), atom(), map()) :: :ok | {:error, term()}
  def broadcast_job_event(%Oban.Job{} = job, event, metadata \\ %{}) do
    Phoenix.PubSub.broadcast(
      Towerops.PubSub,
      @topic,
      %{
        job_id: job.id,
        worker: job.worker,
        device_id: get_in(job.args, ["device_id"]),
        event: event,
        metadata: metadata,
        timestamp: DateTime.utc_now()
      }
    )
  end
end
