import { describe, expect, it, vi } from "vitest"; import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { getApiAdminSnapshot } from "./api-admin.server"; function makeDb() { return { apiKey: { findMany: vi.fn(async () => { const context = getRlsExecutionContext(); expect(context).toMatchObject({ userId: "operator_1", tenantId: "tenant_1" }); return [ { id: "key_1", active: true, expires: null, createdAt: new Date("2026-07-09T09:00:00.000Z") }, { id: "key_2", active: false, expires: new Date("2026-07-08T09:00:00.000Z"), createdAt: new Date("2026-07-08T09:00:00.000Z") }, ]; }), }, apiKeyLog: { count: vi.fn(async () => 1) }, registration: { count: vi.fn(async () => 1), findMany: vi.fn(async () => [ { id: "reg_1", email: "lead@example.test", company: "Acme", createdAt: new Date("2026-07-09T10:00:00.000Z"), createdTenantId: null }, ]), }, adminLead: { count: vi.fn(async () => { expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1" }); return 3; }), findMany: vi.fn(async () => { expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1" }); return [ { id: "lead_1", email: "lead@example.test", company: "Acme", source: { displayName: "HiveGrid Website" }, status: "new", capturedAt: new Date("2026-07-09T10:00:00.000Z"), }, ]; }), }, tenant: { findMany: vi.fn(async () => [ { id: "tenant_1", name: "Acme", slug: "acme", }, ]), }, }; } describe("getApiAdminSnapshot", () => { it("aggregates API keys, logs, consumers, and inbound registrations", async () => { const db = makeDb(); const snapshot = await runWithRlsContext({ userId: "operator_1" }, () => getApiAdminSnapshot({ db: db as never, now: () => new Date("2026-07-09T10:00:00.000Z"), platformLeadVisibility: { actorAdminUserId: "operator_1", canReadAll: false, }, }) ); expect(db.apiKey.findMany).toHaveBeenCalledWith({ orderBy: { createdAt: "desc" }, select: { id: true, active: true, expires: true, createdAt: true }, }); expect(db.apiKeyLog.count).toHaveBeenCalledWith({ where: { status: { gte: 400 } } }); expect(db.adminLead.findMany).toHaveBeenCalledWith( expect.objectContaining({ where: { archivedAt: null, assignedToAdminUserId: "operator_1", }, }) ); expect(snapshot.metrics).toEqual( expect.arrayContaining([ expect.objectContaining({ id: "keys", value: 2 }), expect.objectContaining({ id: "activeKeys", value: 1 }), expect.objectContaining({ id: "expiredKeys", value: 1 }), ]) ); expect(snapshot.consumers[0]).toMatchObject({ name: "Acme", keyCount: 2, activeKeyCount: 1 }); expect(snapshot.inbound.recentRegistrations[0]).toMatchObject({ email: "lead@example.test" }); expect(snapshot.inbound.recentLeads[0]).toMatchObject({ source: "HiveGrid Website", }); }); });