import type { UiMessage } from "@/stores/chat/ui-message";

export type ChatMessageKeyResolver = (message: UiMessage) => string;

export type ChatRenderItem =
  | { type: "date"; date: string; key: string }
  | { type: "msg"; message: UiMessage; key: string };

export function createChatMessageKeyResolver(): ChatMessageKeyResolver {
  return (message) => `msg-${message.displayId}`;
}

export function buildChatRenderItems(
  messages: readonly UiMessage[],
  getMessageKey: ChatMessageKeyResolver,
): ChatRenderItem[] {
  const items: ChatRenderItem[] = [];

  messages.forEach((message, index) => {
    const messageKey = getMessageKey(message);
    if (index === 0 || message.date !== messages[index - 1].date) {
      items.push({
        type: "date",
        date: message.date,
        key: `date-${message.date}-${messageKey}`,
      });
    }
    items.push({ type: "msg", message, key: messageKey });
  });

  return items;
}
