# frozen_string_literal: true

require "forwardable"
require "monitor"

# @api private
module Wayfarer
  module Sidekiq
    module AdapterPool
      class Server
        extend Forwardable
        extend MonitorMixin

        class << self
          attr_writer :pool

          def pool(options = {})
            synchronize do
              @pool ||= Wayfarer::HTTPAdapters::AdapterPool.new(options)
            end
          end
        end

        delegate pool: "self.class"

        def initialize(options = {})
          pool(options)
        end

        def call(worker, _msg, _queue, &block)
          return yield unless worker.is_a?(Wayfarer::Worker)

          pool.with do |adapter|
            worker.adapter = adapter
            yield
          end
        end
      end
    end
  end
end
