// FILE: src/middleware/rbac.js
// RBAC: Role-Based Access Control middleware helpers
// - Role and Permission guard middleware
// - Requires req.user.roles and req.user.permissions to be populated (e.g. via auth.js with enrichment)

export function requireRole(...allowed) {
  return (req, res, next) => {
    const roles = (req.principal?.roles || []).map(r => r.role_code);
    const ok = roles.some((r) => allowed.includes(r)) || req.principal?.is_superadmin;
    if (!ok) return res.status(403).json({ error: "FORBIDDEN_ROLE", need_any_of: allowed });
    next();
  };
}

export function requirePermissionCode(...codes) {
  return (req, res, next) => {
    const p = req.principal;
    if (!p) return res.status(401).json({ error: "Unauthenticated" });
    const ok = p.is_superadmin || codes.some((c) => p.permissions?.has?.(c));
    if (!ok) return res.status(403).json({ error: "FORBIDDEN", need_any_of: codes });
    next();
  };
}
