const requireAuth = (req, res, next) => {
  if (req.session && req.session.user && req.session.user.id) {
    return next();
  }
  res.status(401).json({ success: false, message: "Authentication required" });
};

const requireRole = (allowedRoles) => {
  // Allow single role or array of roles
  const roles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];

  return (req, res, next) => {
    if (!req.session || !req.session.user || !req.session.user.id) {
      return res
        .status(401)
        .json({ success: false, message: "Authentication required" });
    }

    const userRole = req.session.user.role_id || "role-admin";

    if (roles.includes(userRole)) {
      return next();
    }

    res.status(403).json({
      success: false,
      message: "Access denied. Insufficient permissions.",
      required_role: roles,
      your_role: userRole,
    });
  };
};

module.exports = { requireAuth, requireRole };
