# frozen_string_literal: true

require_relative "./xep0122_field"

class BuyAccountCreditForm
	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

	AMOUNT_FIELD =
		XEP0122Field.new(
			"xs:decimal",
			range: (0..1000),
			var: "amount",
			label: "Amount of credit to buy",
			required: true
		).field

	def balance
		{
			type: "fixed",
			value: "Current balance: $#{'%.2f' % @balance}"
		}
	end

	def add_to_form(form)
		form.type = :form
		form.title = "Buy Account Credit"
		form.fields = [
			balance,
			@payment_methods.to_list_single,
			AMOUNT_FIELD
		]
	end

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