import { roleCan } from '../utils/permissions.js';

// Chain after `protect`. Usage: authorize('product.delete') or authorize('a', 'b') (any-of).
export const authorize = (...actions) => (req, res, next) => {
  if (!req.user) {
    return res.status(401).json({ success: false, message: 'Not authorized' });
  }
  if (req.user.status === 'INACTIVE') {
    return res.status(403).json({ success: false, message: 'Account is deactivated' });
  }
  const allowed = actions.some((action) => roleCan(req.user.role, action));
  if (!allowed) {
    return res.status(403).json({
      success: false,
      message: `Forbidden: requires ${actions.join(' or ')}`,
    });
  }
  next();
};
