import assert from "node:assert/strict";
import { test } from "bun:test";

import type { ChatMessage } from "@/types";
import { mergeBoundedProjectionMessages } from "./workbench-message-projection-budget";

function message(input: Partial<ChatMessage> & Pick<ChatMessage, "id" | "role">): ChatMessage {
  return {
    text: "",
    status: "completed",
    createdAt: "2026-07-02T00:00:00.000Z",
    ...input
  } as ChatMessage;
}

test("bounded projection merge keeps the same array when no message changes", () => {
  const existing = [message({ id: "msg_1", role: "agent", traceId: "trc_1", text: "sealed" })];
  assert.equal(mergeBoundedProjectionMessages(existing, existing), existing);
});

test("bounded projection merge patches by trace without replacing unrelated messages", () => {
  const user = message({ id: "msg_user", role: "user", traceId: "trc_1", text: "prompt" });
  const agent = message({ id: "msg_agent", role: "agent", traceId: "trc_1", text: "old" });
  const incoming = message({ id: "msg_agent_next", role: "agent", traceId: "trc_1", text: "new" });
  const existing = [user, agent];
  const merged = mergeBoundedProjectionMessages(existing, [incoming]);

  assert.notEqual(merged, existing);
  assert.equal(merged[0], user);
  assert.equal(merged[1], incoming);
});
