import { getUserById } from 'officerdb';

// Identifies the platform owner. The user's `role` column IS the answer — there is no second mechanism
// and no environment variable.
//
// This used to resolve the owner two other ways: SUPER_ADMIN_EMAIL from .env, falling back to the
// lowest user id. Both are gone. Three sources of truth for "who owns this server" (those two plus the
// role column) disagree the moment one is edited, and the failure is silent — an account quietly gains
// or loses the vault, the platform origin, and the identity the agent sidecar runs as.
//
// NOT CACHED, deliberately. The previous version cached an owner id and justified it with "the owner
// never changes at runtime (bootstrap is closed after user #1)". That stops being true the moment roles
// are editable, and a cache with no invalidation contract is a staleness bug waiting for whoever builds
// the role UI. This is one primary-key lookup on a request that has already verified a JWT.
export async function isSuperAdmin(payload: { id?: number } | null | undefined): Promise<boolean> {
  if (!payload?.id) return false;
  try {
    const user = await getUserById(payload.id);
    return user?.role === 'Super Admin';
  } catch {
    // A transient database error must never promote anyone. Deny, and let the next call retry.
    return false;
  }
}
