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

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    commitDispoImportBatch: vi.fn(),
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    assessDispoImportReadiness: vi.fn(),
    loadResourceDailyAvailabilityContexts: vi.fn().mockResolvedValue(new Map()),
    getDashboardDemand: vi.fn().mockResolvedValue([]),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardOverview: vi.fn(),
    getDashboardSkillGapSummary: vi.fn().mockResolvedValue({
      roleGaps: [],
      totalOpenPositions: 0,
      skillSupplyTop10: [],
      resourcesByRole: [],
    }),
    getDashboardProjectHealth: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getDashboardTopValueResources: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    stageDispoImportBatch: vi.fn(),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-audit-task-test-helpers.js";

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

  it("returns task lists and counts for the current user through the notification router", async () => {
    const db = {
      user: {
        findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
      },
      notification: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "task_1",
            title: "Approve vacation",
            category: "APPROVAL",
            taskStatus: "OPEN",
            priority: "HIGH",
          },
        ]),
        groupBy: vi.fn().mockResolvedValue([
          { taskStatus: "OPEN", _count: 2 },
          { taskStatus: "IN_PROGRESS", _count: 1 },
        ]),
        count: vi.fn().mockResolvedValue(1),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const listResult = await executeTool(
      "list_tasks",
      JSON.stringify({ status: "OPEN", includeAssigned: false, limit: 10 }),
      ctx,
    );
    const countsResult = await executeTool("get_task_counts", "{}", ctx);

    expect(db.notification.findMany).toHaveBeenCalledWith({
      where: {
        userId: "user_1",
        category: { in: ["TASK", "APPROVAL"] },
        taskStatus: "OPEN",
      },
      orderBy: [{ priority: "desc" }, { dueDate: "asc" }, { createdAt: "desc" }],
      take: 10,
    });
    expect(JSON.parse(listResult.content)).toEqual([
      expect.objectContaining({
        id: "task_1",
        title: "Approve vacation",
      }),
    ]);
    expect(JSON.parse(countsResult.content)).toEqual({
      open: 2,
      inProgress: 1,
      done: 0,
      dismissed: 0,
      overdue: 1,
    });
  });
});
