import type { WorkNotice } from "@code/primitives/work";
import { describe, expect, test } from "vitest";

import type { ConversationMessage } from "@/lib/chat/types";

import {
  buildWorkspaceTimeline,
  findSourceMessageTarget,
} from "./presentation";

const textMessage = (
  id: string,
  role: "assistant" | "user",
  text: string
): ConversationMessage => ({
  id,
  parts: [{ state: "done", text, type: "text" }],
  role,
});

const notice: WorkNotice = {
  createdAt: 10,
  eventId: "event-1",
  sourceMessageIds: ["source-1"],
  sourceTexts: ["Build the phone flow."],
  workId: "work-1",
};

describe("Workspace presentation", () => {
  test("places proposed Work after the assistant response to its source", () => {
    const timeline = buildWorkspaceTimeline(
      [
        textMessage("user-1", "user", "Build the phone flow."),
        textMessage("assistant-1", "assistant", "Captured and proposed Work."),
      ],
      [notice]
    );

    expect(
      timeline.map((item) =>
        item.kind === "message" ? item.message.id : item.notice.workId
      )
    ).toEqual(["user-1", "assistant-1", "work-1"]);
  });

  test("finds the exact source message without trimming it", () => {
    const messages = [textMessage("user-1", "user", "  Exact source  ")];
    expect(findSourceMessageTarget(messages, "  Exact source  ")).toBe(
      "user-1"
    );
    expect(findSourceMessageTarget(messages, "Exact source")).toBeUndefined();
  });
});
