import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey, 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-admin-crud-test-helpers.js";

describe("assistant resource admin update and deactivate tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes resource updates through the real resource router path and writes an audit log", async () => {
    const auditCreate = vi.fn().mockResolvedValue({ id: "audit_1" });
    const resourceFindUnique = vi.fn()
      .mockResolvedValueOnce({
        id: "res_1",
        eid: "EMP-001",
        displayName: "Carol Danvers",
      })
      .mockResolvedValueOnce({
        id: "res_1",
        eid: "EMP-001",
        displayName: "Carol Danvers",
        dynamicFields: {},
        blueprintId: null,
      });
    const resourceUpdate = vi.fn().mockResolvedValue({
      id: "res_1",
      eid: "EMP-001",
      displayName: "Captain Marvel",
      resourceRoles: [],
    });
    const ctx = createToolContext(
      {
        resource: {
          findUnique: resourceFindUnique,
          update: resourceUpdate,
        },
        auditLog: {
          create: auditCreate,
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "update_resource",
      JSON.stringify({
        id: "res_1",
        displayName: "Captain Marvel",
        chapter: "Delivery",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        message: "Updated resource Captain Marvel (EMP-001)",
        updatedFields: ["displayName", "chapter"],
      }),
    );
    expect(resourceUpdate).toHaveBeenCalled();
    expect(auditCreate).toHaveBeenCalledTimes(1);
  });

  it("returns a stable assistant error when the resource disappears during update", async () => {
    const ctx = createToolContext(
      {
        resource: {
          findUnique: vi.fn()
            .mockResolvedValueOnce({
              id: "res_1",
              eid: "EMP-001",
              displayName: "Carol Danvers",
            })
            .mockResolvedValueOnce({
              id: "res_1",
              eid: "EMP-001",
              displayName: "Carol Danvers",
              dynamicFields: {},
              blueprintId: null,
            }),
          update: vi.fn().mockRejectedValue({
            code: "P2025",
            message: "Record to update not found.",
          }),
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "update_resource",
      JSON.stringify({ id: "res_1", displayName: "Captain Marvel" }),
      ctx,
    );

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

  it("returns a stable assistant error when the resource disappears during deactivation", async () => {
    const ctx = createToolContext(
      {
        resource: {
          findUnique: vi.fn().mockResolvedValue({
            id: "res_1",
            eid: "EMP-001",
            displayName: "Carol Danvers",
          }),
          update: vi.fn().mockRejectedValue({
            code: "P2025",
            message: "Record to update not found.",
          }),
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "deactivate_resource",
      JSON.stringify({ identifier: "res_1" }),
      ctx,
    );

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