const pool = require('../db');
const orgPermissions = require('../permissions/orgPermissions');

module.exports = function requireOrgPermission(permission) {
  return async function (req, res, next) {
    try {
      const user = req.user;

      if (!user || !user.userId || !user.organizationId) {
        return res.status(401).json({
          error: 'Auth context missing'
        });
      }

      const { userId, organizationId, role } = user;

      // 🔒 Owner always allowed
      if (role === 'owner') {
        req.orgRole = role;
        return next();
      }

      // 🔒 Admin shortcut (if no fine-grained permission passed)
      if (!permission && role === 'admin') {
        req.orgRole = role;
        return next();
      }

      // 🔒 Check fine-grained permission
      if (permission) {
        const allowed = orgPermissions?.[role]?.[permission];
        if (!allowed) {
          return res.status(403).json({
            error: 'Permission denied'
          });
        }
      }

      req.orgRole = role;
      return next();

    } catch (err) {
      console.error('Permission check error:', err);
      return res.status(500).json({
        error: 'Authorization failed'
      });
    }
  };
};
