# frozen_string_literal: true

require "braintree"

# Braintree is not async, so wrap in EM.defer for now
class AsyncBraintree
	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
		@gateway = Braintree::Gateway.new(
			environment: environment,
			merchant_id: merchant_id,
			public_key: public_key,
			private_key: private_key
		)
		@gateway.config.logger = LOG
	end

	def respond_to_missing?(m, *)
		@gateway.respond_to?(m) || super
	end

	def method_missing(m, *args)
		return super unless respond_to_missing?(m, *args)

		EM.promise_defer(klass: PromiseChain) do
			@gateway.public_send(m, *args)
		end
	end

	class PromiseChain < EMPromise
		def respond_to_missing?(*)
			false && super # We don't actually know what we respond to...
		end

		def method_missing(m, *args)
			return super if respond_to_missing?(m, *args)

			self.then { |o| o.public_send(m, *args) }
		end
	end
end
