# frozen_string_literal: true

class CommandList
	include Enumerable

	def self.register(command)
		@commands ||= []
		@commands << command
	end

	def self.for(customer, from_jid)
		args_for(customer, from_jid).then do |kwargs|
			new(@commands.select { |c| c.list_for?(**kwargs) })
		end
	end

	def self.args_for(customer, from_jid)
		registered = customer&.registered?
		args = {
			from_jid: from_jid, customer: customer,
			tel: registered&.phone,
			fwd: customer&.fwd, feature_flags: customer&.feature_flags || [],
			payment_methods: [],
			tn_portable: false
		}
		return EMPromise.resolve(args) unless customer&.plan_name

		EMPromise.all([
			customer.payment_methods,
			args[:tel] && customer.active? && customer.tn_portable?
		]).then do |payment_methods, eligible|
			args.merge(
				payment_methods: payment_methods,
				tn_portable: eligible
			)
		end
	end

	def initialize(commands)
		@commands = commands
	end

	def each(&blk)
		@commands.map { |c| { node: c.node, name: c.name } }.each(&blk)
	end
end
