import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";

import { createToolContext, executeTool } from "./assistant-tools-comments-test-helpers.js";

describe("assistant comment list tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes comment listing through the real comment router path", async () => {
    const db = {
      estimate: {
        findUnique: vi.fn().mockResolvedValue({ id: "est_1" }),
      },
      comment: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "comment_1",
            body: "Initial note",
            resolved: false,
            createdAt: new Date("2026-03-29T09:00:00.000Z"),
            author: { id: "user_1", name: "Assistant User", email: "assistant@example.com", image: null },
            replies: [
              {
                id: "comment_reply_1",
                body: "Reply",
                resolved: false,
                createdAt: new Date("2026-03-29T10:00:00.000Z"),
                author: { id: "user_2", name: "Reviewer", email: "reviewer@example.com", image: null },
              },
            ],
          },
        ]),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const listResult = await executeTool(
      "list_comments",
      JSON.stringify({ entityType: "estimate", entityId: "est_1" }),
      ctx,
    );

    expect(db.comment.findMany).toHaveBeenCalledWith({
      where: {
        entityType: "estimate",
        entityId: "est_1",
        parentId: null,
      },
      include: {
        author: { select: { id: true, name: true, email: true, image: true } },
        replies: {
          include: {
            author: { select: { id: true, name: true, email: true, image: true } },
          },
          orderBy: { createdAt: "asc" },
        },
      },
      orderBy: { createdAt: "asc" },
    });
    expect(db.estimate.findUnique).toHaveBeenCalledWith({
      where: { id: "est_1" },
      select: { id: true },
    });
    expect(JSON.parse(listResult.content)).toEqual([
      {
        id: "comment_1",
        author: "Assistant User",
        body: "Initial note",
        resolved: false,
        createdAt: "2026-03-29T09:00:00.000Z",
        replyCount: 1,
        replies: [
          {
            id: "comment_reply_1",
            author: "Reviewer",
            body: "Reply",
            resolved: false,
            createdAt: "2026-03-29T10:00:00.000Z",
          },
        ],
      },
    ]);
  });
});
