# frozen_string_literal: true

require "savon"

class RegistrationRepo
	def initialize(redis:)
		@redis = redis
		@savon = Savon.client {
			wsdl "https://api.1pcom.net/ws2/DIDManagement.asmx?WSDL"
			convert_request_keys_to :camelcase
		}
	end

	def find(jid)
		@redis.lrange("endstream_registration-#{jid.stripped}", 0, 2)
	end

	def put(jid, *creds)
		setup_endstream_route(*creds, jid).then do |status|
			next status unless status[:code].to_i.zero?

			@redis.rpush(
				"endstream_registration-#{jid.stripped}",
				*creds
			).then { status }
		end
	end

	def delete(jid)
		find(jid).then do |creds|
			next { code: 0 } unless creds&.length&.positive?

			EMPromise.all([
				remove_endstream_route(*creds),
				@redis.del("endstream_registration-#{jid.stripped}")
			]).then { |(status, _)| status }
		end
	end

protected

	def setup_endstream_route(tel, username, password, jid)
		EM.promise_defer {
			@savon.call(
				:did_route_sms_to_xmpp, message: {
					auth: { username: username, password: password },
					dID: tel.sub(/\A\+/, ""),
					xMPP_user:
						ProxiedJID.proxy(jid, CONFIG[:component][:jid]).stripped.to_s
				}
			).body.dig(:did_route_sms_to_xmpp_response, :did_route_sms_to_xmpp_result)
		}
	end

	def remove_endstream_route(tel, username, password)
		EM.promise_defer {
			@savon.call(
				:did_unroute_sms, message: {
					auth: { username: username, password: password },
					dID: tel.sub(/\A\+/, "")
				}
			).body.dig(:did_unroute_sms_response, :did_unroute_sms_result)
		}
	end
end
