import { OuterChat } from "../types/ChatListType";

export function insertChatSorted(
  chats: OuterChat[],
  chatToAdd: OuterChat,
): OuterChat[] {
  // Remove existing chat with same ID (to avoid duplicates)
  chats = chats.filter(
    (c) => c.Records[0].chat_id !== chatToAdd.Records[0].chat_id,
  );

  const newChatTime = new Date(chatToAdd.Records[0].updatedAt).getTime();

  const insertIndex = chats.findIndex((c) => {
    const existingTime = new Date(c.Records[0].updatedAt).getTime();
    // Descending order (newest first)
    return newChatTime > existingTime;
  });

  if (insertIndex === -1) {
    chats.push(chatToAdd); // Older than all — insert at end
  } else {
    chats.splice(insertIndex, 0, chatToAdd); // Insert at correct position
  }

  return chats;
}
