"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getHistory = void 0;
var _client = require("@xmpp/client");
var _createTimeoutPromise = require("./createTimeoutPromise.xmpp");
var _getDataFromXml = require("../../helpers/getDataFromXml");
var _createMessageFromXml = require("../../helpers/createMessageFromXml");
const getHistory = async (client, chatJID, max, before, otherId) => {
  if (typeof chatJID !== 'string') {
    return;
  }
  // If a caller passes a bare local-part (no `@host`), pick a default
  // conference based on the client's actual service URL — never leak a
  // hard-coded dev domain.
  const fixedChatJid = chatJID.includes('@') ? chatJID : (() => {
    const service = client?.options?.service || '';
    const host = service.match(/wss?:\/\/([^:/]+)/)?.[1] || 'xmpp.chat.ethora.com';
    return `${chatJID}@conference.${host}`;
  })();
  const id = otherId ?? `get-history:${Date.now().toString()}`;
  let stanzaHdlrPointer;
  const unsubscribe = () => {
    client.off('stanza', stanzaHdlrPointer);
  };
  const responsePromise = new Promise((resolve, reject) => {
    let messages = [];
    stanzaHdlrPointer = async stanza => {
      const result = stanza.getChild('result');
      if (stanza.is('message') && stanza.attrs.from && stanza.attrs.from.startsWith(fixedChatJid) && result) {
        const messageEl = result.getChild('forwarded')?.getChild('message');
        messages.push(messageEl);
      }
      if (stanza.is('iq') && stanza.attrs.id === id && stanza.attrs.type === 'result') {
        let mainMessages = [];
        for (const msg of messages) {
          const reactions = msg?.getChild('reactions');
          const text = msg.getChild('body')?.getText();
          if (text || reactions) {
            const result = await (0, _getDataFromXml.getDataFromXml)(msg);
            if (!result) {
              return;
            }
            const {
              data,
              id,
              body,
              ...rest
            } = result;
            if (!data) {
              console.log('No data in stanza');
              return;
            }
            const message = await (0, _createMessageFromXml.createMessageFromXml)({
              data,
              id,
              body: body || '',
              ...rest
            });
            mainMessages.push(message);
          }
        }
        resolve(mainMessages);
      }
      if (stanza.is('iq') && stanza.attrs.id === id && stanza.attrs.type === 'error') {
        reject();
      }
    };
    client?.on('stanza', stanzaHdlrPointer);
    const message = (0, _client.xml)('iq', {
      type: 'set',
      to: fixedChatJid,
      id: id
    }, (0, _client.xml)('query', {
      xmlns: 'urn:xmpp:mam:2'
    }, (0, _client.xml)('set', {
      xmlns: 'http://jabber.org/protocol/rsm'
    }, (0, _client.xml)('max', {}, max.toString()), before ? (0, _client.xml)('before', {}, before.toString()) : (0, _client.xml)('before'))));
    client?.send(message).catch(err => console.log('err on load', err));
  });
  const timeoutPromise = (0, _createTimeoutPromise.createTimeoutPromise)(10000);
  try {
    // @ts-ignore
    const res = await Promise.race([responsePromise, timeoutPromise]);
    return res === null ? [] : res;
  } catch (e) {
    // MAM rejects with no value when an iq error returns; the timeout
    // path resolves with null instead of throwing. Either is expected
    // for a room with no history yet — only log if `e` is meaningful.
    if (e !== undefined) {
      console.log('=-> error in', fixedChatJid, e);
    }
    return [];
  } finally {
    unsubscribe();
  }
};
exports.getHistory = getHistory;
//# sourceMappingURL=getHistory.xmpp.js.map