import { beforeEach, describe, expect, it, vi } from "vitest";

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 { SystemRole } from "@capakraken/shared";
import { createToolContext } from "./assistant-tools-insights-scenarios-test-helpers.js";

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

  it("routes insights summary reads through the insights router path", async () => {
    const db = {
      project: {
        findMany: vi.fn().mockResolvedValue([
          {
            budgetCents: 100_000,
            startDate: new Date("2026-03-01T00:00:00.000Z"),
            endDate: new Date("2026-03-31T00:00:00.000Z"),
            demandRequirements: [
              {
                headcount: 3,
                startDate: new Date("2026-03-20T00:00:00.000Z"),
                endDate: new Date("2026-04-05T00:00:00.000Z"),
                _count: { assignments: 1 },
              },
            ],
            assignments: [
              {
                resourceId: "res_1",
                startDate: new Date("2026-03-01T00:00:00.000Z"),
                endDate: new Date("2026-03-31T00:00:00.000Z"),
                hoursPerDay: 8,
                dailyCostCents: 10_000,
                status: "ACTIVE",
              },
            ],
          },
        ]),
      },
      resource: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "res_1",
            availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
          },
        ]),
      },
      assignment: {
        findMany: vi.fn().mockResolvedValue([
          {
            resourceId: "res_1",
            hoursPerDay: 2,
          },
        ]),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const result = await executeTool("get_insights_summary", "{}", ctx);

    expect(db.project.findMany).toHaveBeenCalledWith({
      where: { status: { in: ["ACTIVE", "DRAFT"] } },
      include: {
        demandRequirements: {
          select: {
            headcount: true,
            startDate: true,
            endDate: true,
            _count: { select: { assignments: true } },
          },
        },
        assignments: {
          select: {
            resourceId: true,
            startDate: true,
            endDate: true,
            hoursPerDay: true,
            dailyCostCents: true,
            status: true,
          },
        },
      },
    });
    expect(db.resource.findMany).toHaveBeenCalledWith({
      where: { isActive: true },
      select: { id: true, displayName: true, availability: true },
    });
    expect(db.assignment.findMany).toHaveBeenCalledWith({
      where: {
        status: { in: ["ACTIVE", "CONFIRMED"] },
        startDate: { lte: expect.any(Date) },
        endDate: { gte: expect.any(Date) },
      },
      select: { resourceId: true, hoursPerDay: true },
    });
    expect(JSON.parse(result.content)).toEqual({
      total: 3,
      criticalCount: 2,
      budget: 1,
      staffing: 1,
      timeline: 0,
      utilization: 1,
    });
  });
});
