import { beforeEach, describe, expect, it, vi } from "vitest";
import { ImportBatchStatus } from "@capakraken/db";
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-dispo-test-helpers.js";

describe("assistant dispo import batch list and cancel tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("lists dispo import batches through the real dispo router path", async () => {
    const findMany = vi.fn().mockResolvedValue([
      {
        id: "batch_2",
        status: ImportBatchStatus.STAGED,
        createdAt: new Date("2026-03-30T10:00:00.000Z"),
      },
      {
        id: "batch_1",
        status: ImportBatchStatus.STAGED,
        createdAt: new Date("2026-03-30T09:00:00.000Z"),
      },
    ]);
    const ctx = createToolContext(
      {
        importBatch: {
          findMany,
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "list_dispo_import_batches",
      JSON.stringify({ status: ImportBatchStatus.STAGED, limit: 1 }),
      ctx,
    );

    expect(findMany).toHaveBeenCalledWith({
      where: { status: ImportBatchStatus.STAGED },
      orderBy: { createdAt: "desc" },
      take: 2,
    });
    expect(JSON.parse(result.content)).toEqual({
      items: [
        expect.objectContaining({
          id: "batch_2",
          status: ImportBatchStatus.STAGED,
        }),
      ],
      nextCursor: "batch_1",
    });
  });

  it("cancels a dispo import batch through the real router path", async () => {
    const findUnique = vi.fn().mockResolvedValue({
      id: "batch_1",
      status: ImportBatchStatus.STAGED,
    });
    const update = vi.fn().mockResolvedValue({
      id: "batch_1",
      status: ImportBatchStatus.CANCELLED,
    });
    const ctx = createToolContext(
      {
        importBatch: {
          findUnique,
          update,
        },
        auditLog: {
          create: vi.fn().mockResolvedValue(undefined),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "cancel_dispo_import_batch",
      JSON.stringify({ id: "batch_1" }),
      ctx,
    );

    expect(findUnique).toHaveBeenCalledWith({
      where: { id: "batch_1" },
      select: { id: true, status: true },
    });
    expect(update).toHaveBeenCalledWith({
      where: { id: "batch_1" },
      data: { status: ImportBatchStatus.CANCELLED },
    });
    expect(JSON.parse(result.content)).toEqual({
      id: "batch_1",
      status: ImportBatchStatus.CANCELLED,
    });
  });
});
