const resp = require('../response.js');

module.exports = (requiredGroup = 'User') => (req, res, next) => {
  const groups = req.session?.userGroups;
  const required = String(requiredGroup || '').trim().toLowerCase();

  if (!Array.isArray(groups)) {
    return res.status(403).json(
      resp(
        'Access Denied',
        'Only User group members can access this endpoint.',
        null,
        req,
        false
      )
    );
  }

  const hasGroup = groups.some((name) => String(name || '').trim().toLowerCase() === required);
  if (!hasGroup) {
    return res.status(403).json(
      resp(
        'Access Denied',
        'Only User group members can access this endpoint.',
        null,
        req,
        false
      )
    );
  }

  return next();
};