# frozen_string_literal: true

class PortInOrder
	using FormToH

	def self.parse(customer, form)
		params = form.to_h.slice(
			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
		)
		# If the zip has anything that's not a digit, assume Canada
		if params.dig("Subscriber", "ServiceAddress", "Zip") =~ /[^-\d\s]/
			Canada.new(customer, params)
		else
			new(customer, params)
		end
	end

	def initialize(customer, params)
		@params = params
		@params["CustomerOrderId"] = customer.customer_id
		@params["SiteId"] = CONFIG[:bandwidth_site]
		@params["PeerId"] = CONFIG[:bandwidth_peer]
		@params["ProcessingStatus"] = "DRAFT"
		@params["Subscriber"]["SubscriberType"] ||= "RESIDENTIAL"

		@params["BillingTelephoneNumber"].gsub!(/[^\d]/, "")
		@params["BillingTelephoneNumber"].gsub!(/\A1(\d{10})\Z/) { $1 }
	end

	def customer_id
		@params["CustomerOrderId"]
	end

	def loa_authorizing_person
		"%s %s" % [
			@params.dig("Subscriber", "FirstName"),
			@params.dig("Subscriber", "LastName")
		]
	end

	def to_h
		@params.dup.tap do |h|
			h["LoaAuthorizingPerson"] = loa_authorizing_person
			h["ListOfPhoneNumbers"] = {
				"PhoneNumber" => h["BillingTelephoneNumber"]
			}
		end
	end

	def message(order_id)
		url = "https://dashboard.bandwidth.com/portal/r/a/" \
		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
		"New port-in request for #{customer_id}: #{url}"
	end

	def already_inservice?
		BandwidthIris::InServiceNumber.get(@params["BillingTelephoneNumber"])
		Command.finish(
			"That number is already in service with us. " \
			"Please contact support if you need assistance.",
			type: :error
		)
		true
	rescue BandwidthIris::APIError
		false
	end

	def complete_with
		EMPromise.resolve(self)
	end

	class Canada < PortInOrder
		def message(order_id)
			"#{super} (canadian port from #{@losing_carrier})"
		end

		def complete_with
			yield(FormTemplate.render("lnp_canada")).then { |form|
				@losing_carrier = form.field("LosingCarrier").value
				self
			}
		end
	end
end
