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,
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-user-admin-test-helpers.js";

describe("assistant user admin tools permissions and totp errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable error when setting permissions for a missing user", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "set_user_permissions",
      JSON.stringify({ userId: "user_missing", overrides: { granted: ["manageProjects"] } }),
      ctx,
    );

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

  it("returns a stable error when resetting permissions for a missing user", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "reset_user_permissions",
      JSON.stringify({ userId: "user_missing" }),
      ctx,
    );

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

  it("returns a stable error when reading effective permissions for a missing user", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "get_effective_user_permissions",
      JSON.stringify({ userId: "user_missing" }),
      ctx,
    );

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

  it("returns a stable error when disabling TOTP for a missing user", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "disable_user_totp",
      JSON.stringify({ userId: "user_missing" }),
      ctx,
    );

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