# frozen_string_literal: true

require 'lazy_object'

class RegistrationRepo
	class Conflict < StandardError; end

	def initialize(redis: LazyObject.new { REDIS })
		@redis = redis
	end

	def find(jid)
		REDIS.lrange(cred_key(jid), 0, 3)
	end

	def find_jid(tel)
		REDIS.get(jid_key(tel))
	end

	def put(jid, *creds)
		tel = creds.last

		EMPromise.all([
			find(jid),
			REDIS.set(
				jid_key(tel),
				Blather::JID.new(jid).stripped.to_s,
				"NX", "GET"
			)
		]).then { |(oldcreds, oldjid)|
			if oldjid && oldjid != jid.stripped.to_s
				raise Conflict, "Another user exists for #{tel}"
			end

			if !oldcreds.empty? && oldcreds != creds
				REDIS.set(jid_key(tel), oldjid).then do
					raise Conflict, "Another user exists for #{jid}"
				end
			end
		}.then {
			REDIS.rpush(cred_key(jid), *creds)
		}
	end

protected

	def cred_key(jid)
		"catapult_cred-#{Blather::JID.new(jid).stripped}"
	end

	def jid_key(tel)
		"catapult_jid-#{tel}"
	end
end
