import { describe, expect, it } from "vitest";

import type { UiMessage } from "@/data/dto/chat";

import {
  buildChatRenderItems,
  createChatMessageKeyResolver,
} from "../chat-render-items";

describe("chat area render items", () => {
  it("keeps local message keys stable when history is prepended", () => {
    const localMessage: UiMessage = {
      content: "optimistic message",
      isFromAI: false,
      date: "2026-07-08",
    };
    const historyMessage: UiMessage = {
      id: "history-msg-1",
      content: "history message",
      isFromAI: true,
      date: "2026-07-07",
    };
    const getMessageKey = createChatMessageKeyResolver();

    const firstItems = buildChatRenderItems([localMessage], getMessageKey);
    const secondItems = buildChatRenderItems(
      [historyMessage, localMessage],
      getMessageKey,
    );

    expect(findMessageKey(firstItems, localMessage)).toBe("local-msg-1");
    expect(findMessageKey(secondItems, localMessage)).toBe("local-msg-1");
    expect(findMessageKey(secondItems, historyMessage)).toBe(
      "msg-history-msg-1",
    );
  });
});

function findMessageKey(
  items: ReturnType<typeof buildChatRenderItems>,
  message: UiMessage,
): string | undefined {
  return items.find((item) => item.type === "msg" && item.message === message)
    ?.key;
}
