import { Message, MessageRole, MessageType } from 'src/application/models';

type MessageFinder = {
  msgs: Message[][];
  type?: MessageType;
  role?: MessageRole;
};

export const useMessageFilter = () => {
  const findMessageIndex = ({ msgs, type, role }: MessageFinder) => {
    let lastIndex = -1;
    msgs.forEach((subArray, index) => {
      subArray.forEach(obj => {
        if (obj.type === type || obj.role === role) lastIndex = index;
      });
    });
    return lastIndex;
  };

  const removePreviousDiscussions = (msgs: Message[][], index: number) => {
    if (index > -1) {
      const lastMessages = msgs.slice(index);
      return lastMessages.length > 0 ? lastMessages : msgs;
    }
    return msgs;
  };

  const getFilteredMessages = (msgs: Message[][], skipFilter?: boolean) => {
    const messageMap = msgs.reduce(
      (acc, msg) => {
        acc[msg[0].id] = msg;
        return acc;
      },
      {} as Record<string, Message[]>,
    );
    const deduplicatedMsgs = Object.values(messageMap);
    if (!skipFilter) {
      const idx = findMessageIndex({ msgs: deduplicatedMsgs, type: MessageType.Separator });
      return removePreviousDiscussions(deduplicatedMsgs, idx);
    }
    return deduplicatedMsgs;
  };

  return {
    findMessageIndex,
    removePreviousDiscussions,
    getFilteredMessages,
  };
};
