import type { InfiniteData } from "@tanstack/react-query";
import type { ChatMessage } from "@/components/chat/ChatMessageCard";

export type ChatThreadPage = { messages: ChatMessage[]; nextPage?: number };
export type ChatThreadData = InfiniteData<ChatThreadPage, number>;

export function normalizeThreadId(id: unknown): string {
  if (!id) return "";
  return String(id);
}

export function appendMessageToThreadCache(
  oldData: ChatThreadData | undefined,
  message: ChatMessage
): ChatThreadData {
  if (!oldData?.pages?.length) {
    return {
      pages: [{ messages: [message], nextPage: undefined }],
      pageParams: [1],
    };
  }

  const exists = oldData.pages.some((p) =>
    p.messages.some((m) => m._id === message._id)
  );
  if (exists) return oldData;

  const newPages = [...oldData.pages];
  const firstPage = newPages[0];
  newPages[0] = {
    ...firstPage,
    messages: [...firstPage.messages, message],
  };

  return { ...oldData, pages: newPages };
}
