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 inventory read tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns the active user count for admin users", async () => {
    const count = vi.fn().mockResolvedValue(4);
    const ctx = createToolContext({
      user: {
        count,
      },
    }, SystemRole.ADMIN);

    const result = await executeTool(
      "get_active_user_count",
      JSON.stringify({}),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({ count: 4 });
    expect(count).toHaveBeenCalledWith({
      where: {
        lastActiveAt: {
          gte: expect.any(Date),
        },
      },
    });
  });

  it("lists users only for admins through the real user router", async () => {
    const db = {
      user: {
        findMany: vi.fn().mockResolvedValue([
          { id: "user_1", name: "Alice", email: "alice@example.com" },
          { id: "user_2", name: "Bob", email: "bob@example.com" },
        ]),
      },
    };
    const adminCtx = createToolContext(db, SystemRole.ADMIN);
    const managerCtx = createToolContext({}, SystemRole.MANAGER);

    const adminResult = await executeTool(
      "list_users",
      JSON.stringify({ limit: 1 }),
      adminCtx,
    );
    const deniedResult = await executeTool("list_users", "{}", managerCtx);

    expect(db.user.findMany).toHaveBeenCalledWith({
      select: {
        id: true,
        name: true,
        email: true,
        systemRole: true,
        createdAt: true,
        lastLoginAt: true,
        lastActiveAt: true,
        permissionOverrides: true,
        totpEnabled: true,
        isActive: true,
      },
      orderBy: { name: "asc" },
    });
    expect(JSON.parse(adminResult.content)).toEqual([
      expect.objectContaining({ id: "user_1", name: "Alice" }),
    ]);
    expect(JSON.parse(deniedResult.content)).toEqual(
      expect.objectContaining({
        error: "You do not have permission to perform this action.",
      }),
    );
  });
});
