require_relative "result"
require_relative "delivery"

module Relay
  # Dispatches queued deliveries strictly in order, one at a time.
  #
  # This is deliberate, not an oversight: receivers rely on seeing events in
  # the order they occurred (e.g. "created" before "updated"), and a single
  # in-process worker is the simplest way to guarantee that. Interleaving
  # deliveries would silently break receivers' ordering assumptions.
  class Queue
    def initialize(delivery:)
      @delivery = delivery
      @pending = []
    end

    def enqueue(url, payload)
      @pending << [url, payload]
      Result.ok(@pending.size)
    end

    def drain
      results = []
      until @pending.empty?
        url, payload = @pending.shift
        results << @delivery.deliver(url, payload)
      end
      Result.ok(results)
    end
  end
end
