# frozen_string_literal: true

require "nokogiri"

class LocalCallingGuideRepo
	# @param npa [String] area code (first 3 digits after country code)
	# @param nxx [String] exchange (digits 4-6)
	# @return [EMPromise<Hash{Symbol => Float}>] :lat and :lon of the rate center
	# @raise [RuntimeError] if no prefix data found
	def find(npa, nxx)
		EM::HttpRequest.new(
			"https://localcallingguide.com/xmlprefix.php",
			tls: { verify_peer: true }
		).aget(query: { npa: npa, nxx: nxx }).then { |res|
			doc = Nokogiri::XML.parse(res.response)
			prefix = doc.at("prefixdata")
			raise "No prefix data for #{npa}-#{nxx}" unless prefix

			{
				lat: prefix.at("rc-lat").text.to_f,
				lon: prefix.at("rc-lon").text.to_f
			}
		}
	end
end
