import { describe, expect, it } from "vitest";
import { snapshotToUiMessages } from "../src/dimsdk/core/session-ui-messages.ts";

describe("session ui messages", () => {
  it("restores persisted tool calls with a real call.id", () => {
    const messages = snapshotToUiMessages({
      context: {
        messages: [
          {
            content: "Working on it",
            id: "assistant_1",
            role: "assistant",
            tool_calls: [
              {
                function: {
                  arguments: { file: "/repo/src/app.ts" },
                  name: "Read",
                },
                id: "call_read_1",
              },
            ],
          },
          {
            content: "file contents",
            id: "tool_1",
            role: "tool",
            tool_call_id: "call_read_1",
            toolName: "Read",
          },
        ],
      },
    });

    expect(messages).toHaveLength(2);

    const assistant = messages[0];
    expect(assistant?.role).toBe("assistant");
    if (!assistant || assistant.role !== "assistant") {
      throw new Error("expected restored assistant message");
    }

    const toolCallPart = assistant.parts.find(
      part => part.type === "tool_call",
    );
    expect(toolCallPart?.type).toBe("tool_call");
    if (!toolCallPart || toolCallPart.type !== "tool_call") {
      throw new Error("expected restored tool call part");
    }

    expect(toolCallPart.call.id).toBe("call_read_1");
    expect(toolCallPart.call.name).toBe("Read");
    expect(toolCallPart.call.arguments).toEqual({
      file: "/repo/src/app.ts",
    });

    const toolResultPart = assistant.parts.find(
      part => part.type === "tool_result",
    );
    expect(toolResultPart?.type).toBe("tool_result");
    if (!toolResultPart || toolResultPart.type !== "tool_result") {
      throw new Error("expected restored tool result part");
    }
    expect(toolResultPart.result.toolCallId).toBe("call_read_1");

    const toolMessage = messages[1];
    expect(toolMessage).toMatchObject({
      result: {
        output: "file contents",
        toolCallId: "call_read_1",
      },
      role: "tool",
    });
  });
});
