1# frozen_string_literal: true
 2
 3class BuyAccountCreditForm
 4	class AmountValidationError < StandardError
 5		def initialize(amount)
 6			super("amount #{amount} must be more than $15")
 7		end
 8	end
 9
10	def self.for(customer)
11		customer.payment_methods.then do |payment_methods|
12			new(customer.balance, payment_methods)
13		end
14	end
15
16	def initialize(balance, payment_methods)
17		@balance = balance
18		@payment_methods = payment_methods
19	end
20
21	def form
22		FormTemplate.render(
23			:top_up,
24			balance: @balance,
25			payment_methods: @payment_methods,
26			range: [15, nil]
27		)
28	end
29
30	def parse(form)
31		amount = form.field("amount")&.value&.to_s
32		raise AmountValidationError, amount unless amount.to_i >= 15
33
34		{
35			payment_method: @payment_methods.fetch(
36				form.field("payment_method")&.value.to_i
37			),
38			amount: amount
39		}
40	end
41end