# frozen_string_literal: true

require_relative "backend_sgx"
require_relative "not_loaded"

class TrivialBackendSgxRepo
	def initialize(
		jid: CONFIG[:sgx],
		creds: CONFIG[:creds],
		component_jid: CONFIG[:component][:jid],
		redis: LazyObject.new { REDIS },
		**with
	)
		@jid = Blather::JID.new(jid)
		@creds = creds
		@component_jid = component_jid
		@redis = redis
		@with = with
	end

	def self.get_unregistered(customer_id, **kwargs)
		new(**kwargs).get(customer_id).then { |s| s.with(registered?: false) }
	end

	def get(customer_id, tel: nil)
		use_jid(customer_id).then do |(sgx_jid, creds)|
			BackendSgx.new(
				jid: sgx_jid, creds: creds,
				from_jid: Blather::JID.new("customer_#{customer_id}", @component_jid),
				ogm_url: NotLoaded.new(:ogm_url), fwd: NotLoaded.new(:fwd_timeout),
				transcription_enabled: NotLoaded.new(:transcription_enabled),
				registered?: tel ? ibr_for(tel) : NotLoaded.new(:registered?)
			).with(@with)
		end
	end

	def put(cid, target_sgx, target_num)
		get(cid).then(&:deregister!).then {
			put_jid(cid, target_sgx)
		}.then {
			get(cid)
		}.then { |sgx|
			sgx.register!(target_num)
		}
	end

protected

	def put_jid(cid, target_sgx)
		if target_sgx == CONFIG[:sgx]
			@redis.del("jmp_customer_backend_sgx-#{cid}")
		else
			@redis.set("jmp_customer_backend_sgx-#{cid}", target_sgx)
		end
	end

	def default_jid_creds
		EMPromise.resolve([@jid, @creds])
	end

	def use_jid(customer_id)
		return default_jid_creds unless @jid.node.nil?

		@redis.get("jmp_customer_backend_sgx-#{customer_id}").then do |sgx_jid|
			if sgx_jid
				[Blather::JID.new(sgx_jid), CONFIG[:sgx_creds][sgx_jid.to_sym]]
			else
				default_jid_creds
			end
		end
	end

	def ibr_for(tel)
		ibr = Blather::Stanza::Iq::IBR.new
		ibr.registered = true
		ibr.phone = tel
		ibr
	end
end
