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

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

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

  it("routes allocation status updates 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(
      "update_allocation_status",
      JSON.stringify({ allocationId: "assignment_1", newStatus: "ACTIVE" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(expect.objectContaining({
      success: true,
      message:
        "Updated allocation status: Carol Danvers → Project One (PROJ-1), 2026-06-01 to 2026-06-05: PROPOSED → ACTIVE",
    }));
    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: "ACTIVE",
      }),
    }));
    expect(auditCreate).toHaveBeenCalledTimes(1);
  });
});
