# frozen_string_literal: true

require_relative "trust_level_repo"
require_relative "credit_card_sale"

class BuyAccountCreditForm
	def self.trust_level_repo(**kwargs)
		kwargs[:trust_level_repo] || TrustLevelRepo.new(**kwargs)
	end

	def self.for(customer)
		trust_level_repo.find(customer).then do |trust_level|
			customer.payment_methods.then do |payment_methods|
				new(customer.balance, payment_methods, trust_level.max_top_up_amount)
			end
		end
	end

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

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

	def parse(form)
		amount = form.field("amount")&.value&.to_s

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