# 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(customer_id, target_sgx)
		get(customer_id).then(&:deregister!).then {
			if target_sgx == CONFIG[:sgx]
				@redis.del("jmp_customer_backend_sgx-#{customer_id}")
			else
				@redis.set("jmp_customer_backend_sgx-#{customer_id}", target_sgx)
			end
		}.then { get(customer_id) }
	end

protected

	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
