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

import {
  createAssignment,
  createHappyPathTransaction,
  createToolContext,
  executeTool,
} from "./assistant-tools-allocation-cancel-test-helpers.js";

describe("assistant allocation cancel success tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes allocation cancellation through the real allocation router path", async () => {
    const { assignmentUpdate, auditCreate, transaction } = createHappyPathTransaction();
    const assignment = createAssignment();
    const ctx = createToolContext(
      {
        assignment: {
          findUnique: vi.fn().mockResolvedValue(assignment),
        },
        project: {
          findUnique: vi.fn().mockResolvedValue({
            id: "project_1",
            name: "Project One",
            shortCode: "PROJ-1",
            budgetCents: 0,
          }),
        },
        webhook: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        $transaction: transaction,
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_ALLOCATIONS],
      },
    );

    const result = await executeTool(
      "cancel_allocation",
      JSON.stringify({ allocationId: "assignment_1" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        message:
          "Cancelled allocation: Carol Danvers → Project One (PROJ-1), 2026-06-01 to 2026-06-05",
      }),
    );
    expect(ctx.db.assignment.findUnique).toHaveBeenCalledWith({
      where: { id: "assignment_1" },
      include: expect.objectContaining({
        resource: expect.any(Object),
        project: expect.any(Object),
      }),
    });
    expect(assignmentUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { id: "assignment_1" },
        data: expect.objectContaining({
          status: "CANCELLED",
        }),
      }),
    );
    expect(auditCreate).toHaveBeenCalledTimes(1);
  });
});
