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 password and role errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

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

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

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

  it("returns a stable error when resetting a password that is too short", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn(),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "set_user_password",
      JSON.stringify({ userId: "user_1", password: "short" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(expect.objectContaining({
      error: "Password must be at least 8 characters.",
    }));
    expect(ctx.db.user.findUnique).not.toHaveBeenCalled();
  });

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

    const result = await executeTool(
      "update_user_role",
      JSON.stringify({ id: "user_missing", systemRole: SystemRole.MANAGER }),
      ctx,
    );

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