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

import type { ChatMessage } from "@/types";
import type { TurnStatusAuthority } from "./workbench-session";
import { messageHasSealedTerminalResult, messageIsSealedTerminal, traceAuthorityIsSealed, turnStatusAuthorityIsSealed } from "./workbench-terminal-authority";

function agentMessage(input: Partial<ChatMessage> & Pick<ChatMessage, "status">): ChatMessage {
  return {
    id: `msg_${String(input.status)}`,
    role: "agent",
    title: "Agent",
    text: "",
    createdAt: "2026-07-02T00:00:00.000Z",
    ...input
  };
}

function turnAuthority(input: Partial<TurnStatusAuthority> = {}): TurnStatusAuthority {
  return {
    traceId: "trc_terminal",
    status: "completed",
    terminal: true,
    running: false,
    ...input
  };
}

test("terminal authority requires terminal status and a final body for sealed messages", () => {
  assert.equal(messageIsSealedTerminal(agentMessage({ status: "completed", text: "final answer" })), true);
  assert.equal(messageIsSealedTerminal(agentMessage({ status: "completed" })), false);
  assert.equal(messageIsSealedTerminal(agentMessage({ status: "running", text: "partial" })), false);
});

test("turn authority seals when terminal turn has final response even if message status is stale running", () => {
  const turn = turnAuthority();
  const message = agentMessage({ status: "running", traceId: "trc_terminal", finalResponse: { text: "final answer" } });

  assert.equal(turnStatusAuthorityIsSealed(turn, message), true);
  assert.equal(traceAuthorityIsSealed(turn, message), true);
});

test("terminal result text can come from reply and finalText authority fields", () => {
  assert.equal(messageHasSealedTerminalResult(agentMessage({ status: "running", reply: { finalText: "done" } })), true);
  assert.equal(messageHasSealedTerminalResult(agentMessage({ status: "running", finalText: "done" })), true);
});

test("terminal result keeps finalResponse text content and message field semantics", () => {
  assert.equal(messageHasSealedTerminalResult(agentMessage({ status: "running", finalResponse: { text: "from text" } })), true);
  assert.equal(messageHasSealedTerminalResult(agentMessage({ status: "running", finalResponse: { content: "from content" } })), true);
  assert.equal(messageHasSealedTerminalResult(agentMessage({ status: "running", finalResponse: { message: "from message" } })), true);
});
