defmodule WhoNeedHelp.Push.DeliveryWorker do
  @moduledoc """
  Delivers product push events from PostgreSQL through the configured boundary.

  Event keys remain unique for the lifetime of retained Oban rows. Permanent
  configuration/provider rejections are cancelled; transport and retryable HTTP
  failures use Oban's retry policy.
  """

  use Oban.Worker,
    queue: :push,
    unique: [
      period: :infinity,
      fields: [:args, :worker],
      keys: [:idempotency_key]
    ]

  alias WhoNeedHelp.Push

  @impl Oban.Worker
  def perform(%Oban.Job{
        args:
          %{
            "idempotency_key" => idempotency_key,
            "recipient" => recipient,
            "title" => title,
            "body" => body
          } = args
      }) do
    notification = %{
      idempotency_key: idempotency_key,
      recipient: recipient,
      title: title,
      body: body,
      data: Map.get(args, "data", %{})
    }

    case Push.deliver(notification, Push.delivery_options()) do
      {:ok, _receipt} ->
        :ok

      {:error, :disabled} ->
        {:cancel, :push_disabled}

      {:error, {:invalid_notification, _field} = reason} ->
        {:cancel, reason}

      {:error, {:invalid_option, _option} = reason} ->
        {:cancel, reason}

      {:error, {:rejected, _status, _body} = reason} ->
        {:cancel, reason}

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