"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSuperAdmin = isSuperAdmin;
exports.isGroupAdmin = isGroupAdmin;
exports.canManageRole = canManageRole;
exports.hasGlobalEscalationAccess = hasGlobalEscalationAccess;
exports.hasRolesAsAdmin = hasRolesAsAdmin;
const db_1 = require("../../lib/db");
const roles_1 = require("./roles");
const sql_1 = require("./sql");
// ─── RBAC helpers ─────────────────────────────────────────────────────────────
/**
 * Is the user a superadmin? (global — can manage all users and roles)
 */
async function isSuperAdmin(userId) {
    return (0, roles_1.hasRoleType)(userId, 'superadmin');
}
/**
 * Is the user an admin of a specific role group?
 * Returns true if the user has `type = 'admin'` or `type = 'superadmin'` for that role,
 * OR if the user is a global superadmin (superadmin on any role).
 */
async function isGroupAdmin(userId, role) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.IS_GROUP_ADMIN, [userId, role]);
    return rows.length > 0;
}
/**
 * Can the actor manage members of the given role?
 * Superadmins can manage any role. Admins can manage roles they belong to.
 */
async function canManageRole(actorId, role) {
    return isGroupAdmin(actorId, role);
}
/**
 * Can this user act on escalations across all roles?
 *
 * True for:
 * - superadmin (any role with type 'superadmin')
 * - admin/admin (the named 'admin' role with type 'admin')
 *
 * These users see all escalations, can claim/resolve/escalate across
 * all roles, and can perform bulk actions.
 */
async function hasGlobalEscalationAccess(userId) {
    if (await isSuperAdmin(userId))
        return true;
    const roles = await (0, roles_1.getUserRoles)(userId);
    return roles.some((r) => r.role === 'admin' && r.type === 'admin');
}
/**
 * Batch check: does the user have admin type for ALL specified roles?
 * Single query — replaces the N+1 loop in checkBulkPermission.
 */
async function hasRolesAsAdmin(userId, roles) {
    if (!roles.length)
        return true;
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(`SELECT COUNT(DISTINCT role)::int AS cnt
     FROM lt_user_roles
     WHERE user_id = $1 AND role = ANY($2::text[]) AND type IN ('admin', 'superadmin')`, [userId, roles]);
    return (rows[0]?.cnt ?? 0) >= roles.length;
}
