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

import { mergeConversationMessages } from "./conversation";
import type { ChatMessage } from "../types/domain";

test("mergeConversationMessages replaces a refreshed agent message instead of appending a duplicate", () => {
  const base: ChatMessage[] = [
    message({ id: "msg_user", role: "user", text: "你好", status: "sent" }),
    message({ id: "msg_agent", role: "agent", text: "处理中", status: "running" })
  ];

  const merged = mergeConversationMessages(base, [
    message({ id: "msg_agent", role: "agent", text: "完成回复", status: "completed", updatedAt: "2026-06-05T10:00:00.000Z" })
  ]);

  assert.equal(merged.length, 2);
  const agent = merged[1];
  assert.ok(agent);
  assert.equal(agent.text, "完成回复");
  assert.equal(agent.status, "completed");
});

test("mergeConversationMessages dedupes same trace and role when a refresh generated a new local id", () => {
  const merged = mergeConversationMessages([
    message({ id: "msg_agent_old", role: "agent", text: "旧回复", status: "running" })
  ], [
    message({ id: "msg_agent_new", role: "agent", text: "最终回复", status: "completed" })
  ]);

  assert.equal(merged.length, 1);
  const agent = merged[0];
  assert.ok(agent);
  assert.equal(agent.id, "msg_agent_new");
  assert.equal(agent.text, "最终回复");
});

function message(overrides: Partial<ChatMessage>): ChatMessage {
  return {
    id: "msg_default",
    role: "agent",
    title: "Code Agent",
    text: "",
    status: "running",
    traceId: "trc_issue932_refresh",
    conversationId: "cnv_issue932_refresh",
    sessionId: "ses_issue932_refresh",
    threadId: "thread-issue932-refresh",
    createdAt: "2026-06-05T09:59:00.000Z",
    ...overrides
  };
}
