import test from "node:test"
import assert from "node:assert/strict"

import type { UiChatMessage } from "../src/lib/chat-utils.ts"
import { mergeSessionHistory } from "../src/lib/chat-utils.ts"

test("mergeSessionHistory clears local assistant transient state when server has final content", () => {
  const current: UiChatMessage[] = [{
    id: "assistant-1",
    role: "assistant",
    content: "Final answer",
    createdAt: "2026-05-18T08:00:00.000Z",
    streamState: "streaming",
    statusLabel: "Thinking",
    statusDetail: "Using tools"
  }]
  const nextMessages: UiChatMessage[] = [{
    id: "assistant-1",
    role: "assistant",
    content: "Final answer",
    createdAt: "2026-05-18T08:00:01.000Z"
  }]

  const [message] = mergeSessionHistory(current, nextMessages)

  assert.equal(message.content, "Final answer")
  assert.equal(message.streamState, undefined)
  assert.equal(message.statusLabel, undefined)
  assert.equal(message.statusDetail, undefined)
})

test("mergeSessionHistory preserves active local streaming state when server content is stale", () => {
  const current: UiChatMessage[] = [{
    id: "assistant-1",
    role: "assistant",
    content: "Streaming answer with more text",
    createdAt: "2026-05-18T08:00:00.000Z",
    streamState: "streaming",
    statusLabel: "Thinking",
    statusDetail: "Drafting"
  }]
  const nextMessages: UiChatMessage[] = [{
    id: "assistant-1",
    role: "assistant",
    content: "Streaming answer",
    createdAt: "2026-05-18T08:00:01.000Z"
  }]

  const [message] = mergeSessionHistory(current, nextMessages)

  assert.equal(message.content, "Streaming answer with more text")
  assert.equal(message.streamState, "streaming")
  assert.equal(message.statusLabel, "Thinking")
  assert.equal(message.statusDetail, "Drafting")
})
