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

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

    const result = await executeTool(
      "update_user_name",
      JSON.stringify({ id: "user_missing", name: "Miles Morales" }),
      ctx,
    );

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

  it("returns a stable error when renaming a user without a name", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn(),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "update_user_name",
      JSON.stringify({ id: "user_1", name: "" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(expect.objectContaining({
      error: "Name is required.",
    }));
    expect(ctx.db.user.findUnique).not.toHaveBeenCalled();
  });

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

    const result = await executeTool(
      "update_user_name",
      JSON.stringify({ id: "user_1", name: "x".repeat(201) }),
      ctx,
    );

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