import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";
import {
  createToolContext,
  executeTool,
  withUserLookup,
} from "./assistant-tools-task-workflow-test-helpers.js";

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

  it("maps taskId for get_task_detail through the real router path", async () => {
    const db = withUserLookup({
      notification: {
        findFirst: vi.fn().mockResolvedValue({
          id: "task_7",
          title: "Review timeline",
          category: "TASK",
          userId: "user_1",
          assigneeId: null,
          sender: { id: "user_mgr", name: "Manager", email: "mgr@example.com" },
        }),
      },
    });
    const ctx = createToolContext(db, SystemRole.USER);

    const result = await executeTool(
      "get_task_detail",
      JSON.stringify({ taskId: "task_7" }),
      ctx,
    );

    expect(db.notification.findFirst).toHaveBeenCalledWith({
      where: {
        id: "task_7",
        OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
        category: { in: ["TASK", "APPROVAL"] },
      },
      select: expect.objectContaining({
        id: true,
        title: true,
        sender: { select: { id: true, name: true, email: true } },
      }),
    });
    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        id: "task_7",
        title: "Review timeline",
      }),
    );
  });

  it("returns a stable assistant error for a missing task detail", async () => {
    const ctx = createToolContext(
      withUserLookup({
        notification: {
          findFirst: vi.fn().mockResolvedValue(null),
        },
      }),
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "get_task_detail",
      JSON.stringify({ taskId: "task_missing" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Task not found with the given criteria.",
    });
  });
});
