const checkPermission = (requiredPermission) => {
  return async (req, res, next) => {
    try {
      const user = req.user;

      if (!user) {
        return res.status(401).send({ message: "Unauthorized" });
      }

      // Super admins have all permissions
      if (user.role?.isSuperAdmin || user.role?.value === "superAdmin") {
        return next();
      }

      // Check if user has the required permission
      const permissions = user.role?.permissions || [];
      const hasPermission = permissions.includes(requiredPermission);

      if (hasPermission) {
        return next();
      } else {
        return res.status(403).send({
          message: `Access denied: ${requiredPermission} permission required`,
        });
      }
    } catch (error) {
      console.error("Error checking permission:", error);
      return res.status(500).send({ message: "Internal server error" });
    }
  };
};

export default checkPermission;
