defmodule Berrypod.ActivityLog.ObanTelemetryHandlerTest do
  use Berrypod.DataCase, async: false

  alias Berrypod.ActivityLog
  alias Berrypod.ActivityLog.ObanTelemetryHandler

  describe "handle_event/4" do
    test "logs activity for discarded (exhausted) jobs" do
      metadata = %{
        state: :discard,
        job: %{worker: "Berrypod.Orders.OrderSubmissionWorker", queue: "checkout"},
        reason: RuntimeError.exception("something broke")
      }

      ObanTelemetryHandler.handle_event(
        [:oban, :job, :exception],
        %{duration: 1000},
        metadata,
        []
      )

      [entry] = ActivityLog.list_recent().items

      assert entry.event_type == "job.exhausted"
      assert entry.level == "error"
      assert entry.message =~ "OrderSubmissionWorker"
      assert entry.payload["worker"] == "Berrypod.Orders.OrderSubmissionWorker"
      assert entry.payload["queue"] == "checkout"
      assert entry.payload["error"] =~ "something broke"
    end

    test "ignores non-discard states" do
      metadata = %{
        state: :failure,
        job: %{worker: "SomeWorker", queue: "default"},
        reason: RuntimeError.exception("temporary failure")
      }

      ObanTelemetryHandler.handle_event(
        [:oban, :job, :exception],
        %{duration: 1000},
        metadata,
        []
      )

      assert ActivityLog.list_recent().total_count == 0
    end
  end
end
