# frozen_string_literal: true

require "test_helper"
require "local_calling_guide_repo"

class LocalCallingGuideRepoTest < Minitest::Test
	def test_find_returns_lat_lon
		body = Nokogiri::XML::Builder.new { |xml|
			xml.root do
				xml.prefixdata do
					xml.npa "917"
					xml.nxx "727"
					xml.x "0"
					xml.rc "NEW YORK"
					xml.region "NY"
					xml.send(:"rc-lat", "40.739362")
					xml.send(:"rc-lon", "-73.991043")
				end
				xml.prefixdata do
					xml.npa "917"
					xml.nxx "727"
					xml.x "1"
					xml.rc "NEW YORK"
					xml.region "NY"
					xml.send(:"rc-lat", "40.739362")
					xml.send(:"rc-lon", "-73.991043")
				end
			end
		}.to_xml

		stub_request(
			:get,
			"https://localcallingguide.com/xmlprefix.php?npa=917&nxx=727"
		).to_return(status: 200, body: body)

		prefix = LocalCallingGuideRepo.new.find("917", "727").sync
		assert_equal(40.739362, prefix.lat)
		assert_equal(-73.991043, prefix.lon)
	end
	em :test_find_returns_lat_lon

	def test_prefix_to_h
		body = Nokogiri::XML::Builder.new { |xml|
			xml.root do
				xml.prefixdata do
					xml.rc "NEW YORK"
					xml.region "NY"
					xml.send(:"rc-lat", "40.739362")
					xml.send(:"rc-lon", "-73.991043")
				end
			end
		}.to_xml

		stub_request(
			:get,
			"https://localcallingguide.com/xmlprefix.php?npa=917&nxx=727"
		).to_return(status: 200, body: body)

		prefix = LocalCallingGuideRepo.new.find("917", "727").sync
		assert_equal(
			{ "region" => "NY", "locality" => "NEW YORK" },
			prefix.to_h
		)
	end
	em :test_prefix_to_h

	def test_find_raises_on_missing_data
		# Applying Style/SymbolProc causes Nokogiri
		# to raise with "Cannot creating bind from C-level Proc"
		body = Nokogiri::XML::Builder.new { |xml| # rubocop:disable Style/SymbolProc
			xml.root
		}.to_xml

		stub_request(
			:get,
			"https://localcallingguide.com/xmlprefix.php?npa=000&nxx=000"
		).to_return(status: 200, body: body)

		assert_raises(RuntimeError) do
			LocalCallingGuideRepo.new.find("000", "000").sync
		end
	end
	em :test_find_raises_on_missing_data
end
