# frozen_string_literal: true

require "blather"
require "value_semantics/monkey_patched"

require_relative "customer_fwd"
require_relative "not_loaded"

class BackendSgx
	value_semantics do
		jid Blather::JID
		creds HashOf(Symbol => String)
		from_jid Blather::JID
		ogm_url Either(String, nil, NotLoaded)
		fwd Either(CustomerFwd, nil, NotLoaded)
		transcription_enabled Either(Bool(), NotLoaded)
		registered? Either(Blather::Stanza::Iq::IBR, FalseClass, NotLoaded)
	end

	def register!(tel)
		iq = ibr
		iq.phone = tel
		IQ_MANAGER.write(iq).then do
			REDIS.set("catapult_jid-#{tel}", from_jid.to_s)
		end
	end

	def deregister!
		ibr = Blather::Stanza::Iq::IBR.new(:set, @jid)
		ibr.from = from_jid
		ibr.remove!
		IQ_MANAGER.write(ibr)
	end

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

	def set_ogm_url(url)
		REDIS.set("catapult_ogm_url-#{from_jid}", url)
	end

protected

	def ibr
		s = Blather::Stanza::Iq::IBR.new(:set, jid)
		s.from = from_jid
		s.nick = creds[:account]
		s.username = creds[:username]
		s.password = creds[:password]
		s
	end
end
