"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ensureScopedChatCache = ensureScopedChatCache;
var _roomStore = require("../roomStore");
var _chatSettingsSlice = require("../roomStore/chatSettingsSlice");
var _roomsSlice = require("../roomStore/roomsSlice");
var _useLocalStorage = require("../hooks/useLocalStorage");
var _LOCAL_STORAGE = require("./constants/LOCAL_STORAGE");
var _rooms = require("../networking/api-requests/rooms.api");
var _persistence = require("../roomStore/persistence");
var _clientRegistry = require("../utils/clientRegistry");
const SCOPE_KEY = '@ethora/chat-component-scope';
/**
 * Detect an app-scope change (different appId / baseUrl). When detected,
 * purge the persisted user, redux user/client/rooms state, REST caches,
 * and the global xmpp client singleton so the next bootstrap re-resolves
 * against the new tenant. Mirrors web ensureScopedChatCache.
 */
async function ensureScopedChatCache(config) {
  if (!config?.appId && !config?.baseUrl) {
    return;
  }
  const next = {
    appId: config.appId,
    baseUrl: config.baseUrl
  };
  const scopeStore = (0, _useLocalStorage.asyncLocalStorage)(SCOPE_KEY);
  const previous = await scopeStore.get();
  const changed = previous && (previous.appId !== next.appId || previous.baseUrl !== next.baseUrl);
  if (changed) {
    try {
      const client = (0, _clientRegistry.getGlobalXmppClient)();
      if (client) {
        await client.disconnect?.({
          suppressReconnect: true
        });
      }
    } catch {
      /* noop */
    }
    (0, _clientRegistry.setGlobalXmppClient)(null);
    (0, _rooms.clearRoomsRestCache)();
    _roomStore.store.dispatch((0, _roomsSlice.setLogoutState)());
    _roomStore.store.dispatch((0, _chatSettingsSlice.logout)());
    await (0, _useLocalStorage.asyncLocalStorage)(_LOCAL_STORAGE.localStorageConstants.ETHORA_USER).remove();
    await (0, _persistence.clearPersistedState)();
  }
  await scopeStore.set(next);
}
//# sourceMappingURL=ensureScopedChatCache.js.map