# frozen_string_literal: true

class BuyAccountCreditForm
	class AmountValidationError < StandardError
		def initialize(amount)
			super("amount #{amount} must be more than $15")
		end
	end

	def self.for(customer)
		customer.payment_methods.then do |payment_methods|
			new(customer.balance, payment_methods)
		end
	end

	def initialize(balance, payment_methods)
		@balance = balance
		@payment_methods = payment_methods
	end

	def form
		FormTemplate.render(
			:top_up,
			balance: @balance,
			payment_methods: @payment_methods,
			range: [15, nil]
		)
	end

	def parse(form)
		amount = form.field("amount")&.value&.to_s
		raise AmountValidationError, amount unless amount.to_i >= 15

		{
			payment_method: @payment_methods.fetch(
				form.field("payment_method")&.value.to_i
			),
			amount: amount
		}
	end
end
