defmodule Berrypod.ActivityLog.ObanTelemetryHandler do
  @moduledoc """
  Captures Oban job exhaustion (all retries failed) as activity log entries.
  Attached in Application.start/2.
  """

  def attach do
    :telemetry.attach(
      "activity-log-oban-exhausted",
      [:oban, :job, :exception],
      &__MODULE__.handle_event/4,
      []
    )
  end

  def handle_event([:oban, :job, :exception], _measurements, metadata, _config) do
    # Only log when job is being discarded (exhausted all retries)
    if metadata.state == :discard do
      worker = metadata.job.worker
      queue = metadata.job.queue
      error = Exception.message(metadata.reason)

      Berrypod.ActivityLog.log_event(
        "job.exhausted",
        "Background job exhausted all retries: #{worker}",
        level: "error",
        payload: %{
          worker: worker,
          queue: queue,
          error: String.slice(error, 0, 500)
        }
      )
    end
  end
end
