"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.reactionsMiddleware = void 0;
var _roomsSlice = require("../roomsSlice");
var _nanoToMs = require("../../helpers/nanoToMs");
const reactionsMiddleware = storeAPI => next => action => {
  if (action.type !== 'roomMessages/setReactions') {
    return next(action);
  }
  if (!action.payload || typeof action.payload !== 'object') {
    console.error('Invalid action payload for setReactions:', action);
    return next(action);
  }
  const result = next(action);
  const state = storeAPI.getState();
  const rooms = state.rooms.rooms;
  const {
    roomJID,
    reactions,
    latestReactionTimestamp,
    data,
    ...rest
  } = action.payload;
  const updLastMessage = () => {
    if (!reactions?.[0]) {
      const newLastMessage = rooms[roomJID].messages[rooms[roomJID].messages.length - 1];
      storeAPI.dispatch((0, _roomsSlice.updateRoom)({
        jid: roomJID,
        updates: {
          lastMessageTimestamp: (0, _nanoToMs.nanoToMs)(rooms[roomJID].messages[rooms[roomJID].messages.length - 1].id) ?? 0,
          lastMessage: newLastMessage
        }
      }));
    } else {
      const updates = {
        lastMessageTimestamp: (0, _nanoToMs.nanoToMs)(latestReactionTimestamp) ?? 0,
        lastMessage: {
          ...rest,
          body: reactions[0],
          emoji: reactions[0],
          user: {
            name: `${data.senderFirstName} ${data.senderLastName}`,
            id: `emoji-${new Date().toString()}`
          },
          date: new Date((0, _nanoToMs.nanoToMs)(latestReactionTimestamp) ?? 0).toISOString()
        }
      };
      storeAPI.dispatch((0, _roomsSlice.updateRoom)({
        jid: roomJID,
        updates: updates
      }));
    }
  };
  if (!rooms[roomJID]) {
    console.warn(`Room ${roomJID} not found in reactions middleware`);
    return result;
  }
  if ((rooms[roomJID]?.lastMessageTimestamp ?? 0) <= ((0, _nanoToMs.nanoToMs)(latestReactionTimestamp) ?? 0)) {
    updLastMessage();
  } else if (!rooms[roomJID]?.lastMessageTimestamp) {
    updLastMessage();
  }
  return result;
};
exports.reactionsMiddleware = reactionsMiddleware;
//# sourceMappingURL=reactionsMiddleware.js.map