# frozen_string_literal: true

class BackendSgx
	def initialize(customer_id, jid=CONFIG[:sgx], creds=CONFIG[:creds])
		@customer_id = customer_id
		@jid = jid
		@creds = creds
	end

	def register!(tel)
		ibr = mkibr(:set)
		ibr.nick = @creds[:account]
		ibr.username = @creds[:username]
		ibr.password = @creds[:password]
		ibr.phone = tel
		IQ_MANAGER.write(ibr)
	end

	def registered?
		IQ_MANAGER.write(mkibr(:get)).catch { nil }.then do |result|
			if result&.respond_to?(:registered?) && result&.registered?
				result
			else
				false
			end
		end
	end

	def stanza(s)
		s.dup.tap do |stanza|
			stanza.to = stanza.to.with(domain: @jid)
			stanza.from = from_jid.with(resource: stanza.from.resource)
		end
	end

	def set_fwd_timeout(timeout)
		REDIS.set("catapult_fwd_timeout-#{from_jid}", timeout)
	end

protected

	def from_jid
		Blather::JID.new(
			"customer_#{@customer_id}",
			CONFIG[:component][:jid]
		)
	end

	def mkibr(type)
		ibr = IBR.new(type, @jid)
		ibr.from = from_jid
		ibr
	end
end
