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

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

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 = {
      displayId: "client:message:local-1",
      content: "optimistic message",
      isFromAI: false,
      date: "2026-07-08",
    };
    const historyMessage: UiMessage = {
      displayId: "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(
      "msg-client:message:local-1",
    );
    expect(findMessageKey(secondItems, localMessage)).toBe(
      "msg-client:message:local-1",
    );
    expect(findMessageKey(secondItems, historyMessage)).toBe(
      "msg-history-msg-1",
    );
  });

  it("derives the same key after a message object is recreated", () => {
    const getMessageKey = createChatMessageKeyResolver();
    const original: UiMessage = {
      displayId: "server:message-1:assistant",
      remoteId: "message-1",
      content: "Original",
      isFromAI: true,
      date: "2026-07-20",
    };
    const updated: UiMessage = {
      ...original,
      content: "Unlocked",
      locked: false,
    };

    expect(getMessageKey(updated)).toBe(getMessageKey(original));
  });
});

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