"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.clearRoomsRestCache = clearRoomsRestCache;
exports.deleteRoom = deleteRoom;
exports.deleteRoomMember = deleteRoomMember;
exports.getRoomByName = getRoomByName;
exports.getRooms = getRooms;
exports.postAddRoomMember = postAddRoomMember;
exports.postPrivateRoom = postPrivateRoom;
exports.postReportRoom = postReportRoom;
exports.postRoom = postRoom;
var _roomStore = require("../../roomStore");
var _roomsSlice = require("../../roomStore/roomsSlice");
var _apiClient = _interopRequireDefault(require("../apiClient"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
 * Materialize a REST `/chats/my` item into an `IRoom` + dispatch
 * `addRoom`. Without this, REST-fetched rooms never make it into
 * `state.rooms.rooms` and `ChatRoom` falls back to the "no rooms,
 * create one!" empty state even when the user has rooms server-side.
 *
 * The room jid is derived from the conference host. We try several
 * places:
 *   1. explicit `room.jid` from the server (if present)
 *   2. `<name>@conference.<xmppHost>` where xmppHost comes from the
 *      provider's `xmppSettings.host` saved to `chatSettingStore.config`
 *   3. derive host from `config.baseUrl` (api.<host> → xmpp.<host>)
 *      as a last-resort heuristic for misconfigured deployments
 *   4. otherwise: skip the room with a warn log (NEVER fall back to a
 *      hardcoded vendor host — previously `xmpp.chat.ethora.com`, which
 *      manifested as a phantom "ethora" room stub on third-party servers,
 *      customer-reported #23)
 */
function dispatchRoomsFromRestItems(items) {
  if (!items?.length) return;
  const config = _roomStore.store.getState().chatSettingStore?.config;
  // Best: explicit xmpp settings.
  let host = config?.xmppSettings?.host || config?.xmppSettings?.conference?.replace(/^conference\./, '');
  // Heuristic fallback: derive xmpp host from the REST baseUrl.
  // `https://api.foo.com/v1` → `xmpp.foo.com`. Better than a hardcoded
  // vendor host and right in 99% of single-domain deployments.
  if (!host && typeof config?.baseUrl === 'string') {
    const m = /^https?:\/\/(?:api\.)?([^/]+)/i.exec(config.baseUrl);
    if (m && m[1]) {
      host = `xmpp.${m[1].replace(/^api\./, '')}`;
    }
  }
  const conference = config?.xmppSettings?.conference || (host ? `conference.${host}` : undefined);
  for (const item of items) {
    if (!item) continue;
    let jid = item.jid;
    if (!jid) {
      if (!conference) {
        // No server-supplied JID and no way to synthesize one safely —
        // skip rather than create a phantom room on a wrong host.
        // Consumers who hit this should set config.xmppSettings.host.
        console.warn(`[ethora-rn] rooms.api: skipping room "${item.name}" — no item.jid and no xmppSettings.host / baseUrl to derive host from`);
        continue;
      }
      jid = `${item.name}@${conference}`;
    }
    if (!jid.includes('@')) continue;
    const room = {
      id: item._id || jid,
      jid,
      name: item.name,
      title: item.title || item.name,
      usersCnt: item.participants ?? item.members?.length ?? 0,
      messages: [],
      isLoading: false,
      roomBg: '',
      icon: item.picture || item.icon,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt,
      description: item.description,
      type: item.type,
      // ChatProfileModal renders this list under the description/type
      // fields. The REST API returns `members` (an array of {_id,
      // firstName?, lastName?}); map to the shape RoomMember expects.
      roomMembers: (item.members || []).map(m => ({
        firstName: m.firstName,
        lastName: m.lastName,
        xmppUsername: m._id || '',
        role: m.role,
        ban_status: m.ban_status,
        last_active: m.last_active,
        jid: m.jid || ''
      }))
    };
    _roomStore.store.dispatch((0, _roomsSlice.addRoom)({
      roomData: room
    }));
  }
}
const GET_ROOMS_CACHE_MS = 60_000;
let getRoomsInFlight = null;
let getRoomsInFlightToken = '';
let lastGetRoomsResponse = null;
let lastGetRoomsResponseAt = 0;
let lastGetRoomsResponseToken = '';

/**
 * REST equivalent of getRoomsStanza. Used by initBeforeLoad to prefetch
 * the room list in parallel with the XMPP handshake. Results are cached
 * per-token for 60s so a downstream re-fetch on mount is a no-op.
 */
async function getRooms() {
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  const now = Date.now();
  if (lastGetRoomsResponse && lastGetRoomsResponseToken === token && now - lastGetRoomsResponseAt < GET_ROOMS_CACHE_MS) {
    return lastGetRoomsResponse;
  }
  if (getRoomsInFlight && getRoomsInFlightToken === token) {
    return getRoomsInFlight;
  }
  getRoomsInFlightToken = token;
  getRoomsInFlight = (async () => {
    const response = await _apiClient.default.get('/chats/my', {
      headers: {
        Authorization: token
      }
    });
    lastGetRoomsResponse = response.data;
    lastGetRoomsResponseAt = Date.now();
    lastGetRoomsResponseToken = token;
    dispatchRoomsFromRestItems(response.data?.items || []);
    return response.data;
  })();
  try {
    return await getRoomsInFlight;
  } catch (error) {
    console.log('Error loading rooms via REST', error);
    return {
      items: []
    };
  } finally {
    getRoomsInFlight = null;
    getRoomsInFlightToken = '';
  }
}
async function getRoomByName(chatName) {
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.get(`/chats/my/${chatName}`, {
      headers: {
        Authorization: token
      }
    });
    return response.data;
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function postRoom(data) {
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.post('/chats', data, {
      headers: {
        Authorization: token
      }
    });
    return response.data.result;
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function postPrivateRoom(username, title = 'Private chat') {
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.post('/chats/private', {
      username
    }, {
      headers: {
        Authorization: token
      }
    });
    return response.data.result;
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function postReportRoom(data) {
  const {
    chatName,
    category,
    text
  } = data;
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.post(`/chats/reports/${chatName}`, {
      category,
      text
    }, {
      headers: {
        Authorization: token
      }
    });
    return response.data.result;
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function postAddRoomMember(data) {
  const {
    chatName,
    members
  } = data;
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.post(`/chats/users-access`, {
      chatName,
      members
    }, {
      headers: {
        Authorization: token
      }
    });
    return response?.data?.results || [];
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function deleteRoomMember(data) {
  const {
    roomId,
    members
  } = data;
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.delete(`/chats/users-access`, {
      headers: {
        Authorization: token
      },
      data: {
        chatName: roomId,
        members
      }
    });
    return response.data.result;
  } catch (error) {
    throw new Error('Error updating profile');
  }
}
async function deleteRoom(name) {
  const token = _roomStore.store.getState().chatSettingStore.user.token || '';
  try {
    const response = await _apiClient.default.delete('/chats', {
      headers: {
        Authorization: token
      },
      data: {
        name
      }
    });
    return response.data.result;
  } catch (error) {
    throw new Error('Error deleting room');
  }
}
function clearRoomsRestCache() {
  lastGetRoomsResponse = null;
  lastGetRoomsResponseAt = 0;
  lastGetRoomsResponseToken = '';
}
//# sourceMappingURL=rooms.api.js.map