# frozen_string_literal: true

require "json"

require_relative "geo_code_repo"

class AreaCodeRepo
	def initialize(db: DB, geo_code_repo: GeoCodeRepo.new)
		@db = db
		@geo_code_repo = geo_code_repo
	end

	def find(q, limit: 3)
		@geo_code_repo.find(q).then { |geo|
			log.debug "AreaCodeRepo#find(#{q.inspect})"
			@db.query_defer(<<~SQL, [geo.country, geo.sql_point, limit])
				SELECT area_code FROM area_codes
				WHERE country=$1
				ORDER BY location <-> $2
				LIMIT $3
			SQL
		}.then { |rows| rows.map { |row| row["area_code"] } }
	end
end
