import { userHasPermission, userCanViewPage } from "../services/accessControl.js";

export function requireRoles(...roles) {
  return (req, res, next) => {
    if (!roles.includes(req.user?.role)) {
      return res.status(403).json({ error: "Keine Berechtigung" });
    }
    next();
  };
}

export function requirePermission(permissionKey, fallbackRoles = []) {
  return async (req, res, next) => {
    try {
      const allowed = await userHasPermission(req.user?.sub, req.user?.role, permissionKey);
      if (!allowed) return res.status(403).json({ error: "Keine Berechtigung" });
      next();
    } catch (err) {
      // Fallback greift nur, falls die neue Permission-Matrix noch nicht migriert ist.
      if (fallbackRoles.includes(req.user?.role)) return next();
      next(err);
    }
  };
}

export function requirePageAccess(pageKey, fallbackRoles = []) {
  return async (req, res, next) => {
    try {
      const allowed = await userCanViewPage(req.user?.sub, req.user?.role, pageKey);
      if (!allowed) return res.status(403).json({ error: "Keine Berechtigung für diese Seite" });
      next();
    } catch (err) {
      // Fallback greift nur, falls die neue Permission-Matrix noch nicht migriert ist.
      if (fallbackRoles.includes(req.user?.role)) return next();
      next(err);
    }
  };
}
