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

import {
  createExistingAssignment,
  createToolContext,
  executeTool,
} from "./assistant-tools-timeline-shifts-test-helpers.js";

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

  it("batch-shifts timeline allocations through the real timeline router mutation", async () => {
    const existingAssignment = createExistingAssignment();

    const db = {
      allocation: {
        findUnique: vi.fn().mockResolvedValue(null),
      },
      demandRequirement: {
        findUnique: vi.fn().mockResolvedValue(null),
      },
      assignment: {
        findUnique: vi.fn().mockResolvedValue(existingAssignment),
        update: vi.fn().mockResolvedValue({
          ...existingAssignment,
          startDate: new Date("2026-03-18"),
          endDate: new Date("2026-03-22"),
        }),
      },
      auditLog: {
        create: vi.fn().mockResolvedValue({}),
      },
      $transaction: vi.fn(async (callback: (tx: unknown) => unknown) => callback(db)),
    };
    const ctx = createToolContext(
      db,
      [PermissionKey.MANAGE_ALLOCATIONS, PermissionKey.USE_ASSISTANT_ADVANCED_TOOLS],
      SystemRole.MANAGER,
    );

    const result = await executeTool(
      "batch_shift_timeline_allocations",
      JSON.stringify({
        allocationIds: ["assignment_1"],
        daysDelta: 2,
        mode: "move",
      }),
      ctx,
    );

    expect(result.action).toEqual({ type: "invalidate", scope: ["allocation", "timeline", "project"] });
    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        count: 1,
      }),
    );
    expect(db.assignment.update).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { id: "assignment_1" },
      }),
    );
  });
});
