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

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { countPlanningEntries } from "@capakraken/application";
import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-master-data-mutation-test-helpers.js";

describe("assistant org unit mutation tools - errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(countPlanningEntries).mockResolvedValue({ countsByRoleId: new Map() });
  });

  it("returns a stable error when creating an org unit with a missing parent", async () => {
    const ctx = createToolContext(
      {
        orgUnit: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "create_org_unit",
      JSON.stringify({ name: "Delivery", level: 6, parentId: "ou_missing" }),
      ctx,
    );

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

  it("returns a stable error when creating an org unit with an invalid child level", async () => {
    const ctx = createToolContext(
      {
        orgUnit: {
          findUnique: vi.fn().mockResolvedValue({
            id: "ou_parent",
            name: "Delivery",
            shortName: "DEL",
            level: 6,
            parentId: null,
            sortOrder: 1,
            isActive: true,
          }),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "create_org_unit",
      JSON.stringify({ name: "Delivery Germany", level: 5, parentId: "ou_parent" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(expect.objectContaining({
      error: "Org unit level must be greater than the parent org unit level.",
    }));
  });

  it("returns a stable error when updating a missing org unit", async () => {
    const ctx = createToolContext(
      {
        orgUnit: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "update_org_unit",
      JSON.stringify({ id: "ou_missing", name: "Delivery Europe" }),
      ctx,
    );

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