// Audit Class 1 — requirePlatformAdmin role-matrix [DIRECT-DEV] verification.
//
// requirePlatformAdmin (server/lib/rbac-middleware.ts) is the global-role gate that
// closes the resolveEffectiveRole "admin-trap" on PLATFORM-SCOPED routes (in-memory /
// RLS-exempt / global state where RLS gives no backstop). This suite proves the role
// matrix the ledger requires: platform-global admin -> pass; a tenant-scoped admin
// (whose GLOBAL users.role is non-admin) -> 403; unauthenticated -> 401.
//
// Requires DATABASE_URL + the boot secrets (runs under test:integration). storage.getUser
// reads the seeded users from the throwaway DB.

import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { eq } from "drizzle-orm";
import { db } from "../server/db.js";
import { users } from "../shared/schema.js";
import { requirePlatformAdmin } from "../server/lib/rbac-middleware.js";

const RUN = `pa-test-${Date.now()}`;
const GLOBAL_ADMIN_ID = `${RUN}-global-admin`;
const TENANT_ADMIN_ID = `${RUN}-tenant-admin`;
const GA_USER = `${RUN}-ga`;
const TA_USER = `${RUN}-ta`;

// Invoke the middleware with a mock req/res and capture the outcome.
async function invoke(userId: string | undefined): Promise<{ status: number; nexted: boolean }> {
  const req: any = { session: { userId }, traceId: "test", path: "/api/test-platform" };
  let status = 200;
  let nexted = false;
  const res: any = {
    status(c: number) { status = c; return this; },
    json(_: unknown) { return this; },
  };
  await requirePlatformAdmin(req, res, () => { nexted = true; });
  return { status, nexted };
}

describe("Audit Class 1 — requirePlatformAdmin global-role gate", () => {
  before(async () => {
    await db.delete(users).where(eq(users.username, GA_USER));
    await db.delete(users).where(eq(users.username, TA_USER));
    // Platform-global admin: users.role = 'admin'.
    await db.insert(users).values({ id: GLOBAL_ADMIN_ID, username: GA_USER, password: "x", role: "admin", fullName: "Global Admin" });
    // Tenant-scoped admin: their GLOBAL users.role is NON-admin (e.g. risk_manager). Their
    // tenant 'admin' role would live in user_tenant_roles and resolveEffectiveRole WOULD
    // confer effective 'admin' (the trap) — but requirePlatformAdmin checks the global role.
    await db.insert(users).values({ id: TENANT_ADMIN_ID, username: TA_USER, password: "x", role: "risk_manager", fullName: "Tenant Admin" });
  });

  after(async () => {
    await db.delete(users).where(eq(users.id, GLOBAL_ADMIN_ID));
    await db.delete(users).where(eq(users.id, TENANT_ADMIN_ID));
  });

  test("platform-global admin (users.role='admin') passes -> 200", async () => {
    const r = await invoke(GLOBAL_ADMIN_ID);
    assert.equal(r.nexted, true, "global admin must pass requirePlatformAdmin");
    assert.equal(r.status, 200);
  });

  test("tenant-scoped admin (global users.role != 'admin') is blocked -> 403", async () => {
    const r = await invoke(TENANT_ADMIN_ID);
    assert.equal(r.nexted, false, "a tenant-scoped admin must NOT pass a platform gate (admin-trap closed)");
    assert.equal(r.status, 403);
  });

  test("unauthenticated (no session) -> 401", async () => {
    const r = await invoke(undefined);
    assert.equal(r.nexted, false);
    assert.equal(r.status, 401);
  });
});
