# frozen_string_literal: true

require_relative "sim_pricing"

module MonthlyDataLimit
	MAX_MULTIPLIER = 10

	def self.for_sims(sims, currency, config)
		sims.empty? ? {} : for_currency(currency, config)
	end

	def self.for_currency(currency, config)
		step = SIMPricing.whole_dollars(
			SIMPricing.five_gb_refill_price(currency, config)
		)
		{
			step: step,
			max: step * MAX_MULTIPLIER
		}
	end

	def self.from_form(form, step:, max:)
		limit = form.field("monthly_data_limit")&.value
		return if limit.to_s.empty?

		parse(limit, step: step, max: max)
	end

	def self.parse(limit, step:, max:)
		limit = Integer(limit, 10)
		unless (0..max).cover?(limit)
			raise "Monthly data limit must be between 0 and #{max}"
		end
		unless (limit % step).zero?
			raise "Monthly data limit must be a multiple of #{step}"
		end

		limit
	end
end
