const User = require('../models/User');
const Role = require('../models/Role');
const { ForbiddenError } = require('../utils/errors');

/**
 * Middleware to check if user has specific permission
 * @param {string} userId - User ID
 * @param {string} permission - Permission to check (e.g., 'picker_packer_view')
 * @returns {Promise<boolean>} - Returns true if user has permission
 */
const checkPermission = async (userId, permission) => {
  try {
    // Get user with role
    const user = await User.findById(userId).select('role');

    // If user not found, deny access
    if (!user) {
      return false;
    }

    // Super admin has all permissions
    if (user.role === 'superadmin') {
      return true;
    }

    // For now, allow all authenticated users with any role
    // TODO: Implement proper permission checking based on role
    return true;
  } catch (error) {
    console.error('Permission check error:', error);
    return false;
  }
};

/**
 * Express middleware to check permission
 * @param {...string} permissions - List of permissions to check
 * @returns {Function} - Express middleware function
 */
const authorize = (...permissions) => {
  return async (req, res, next) => {
    try {
      if (!req.user) {
        throw new ForbiddenError('Authentication required');
      }

      // Check each required permission
      for (const permission of permissions) {
        const hasPermission = await checkPermission(req.user.id, permission);
        if (!hasPermission) {
          throw new ForbiddenError('Insufficient permissions');
        }
      }
      
      next();
    } catch (error) {
      next(error);
    }
  };
};

module.exports = {
  checkPermission,
  authorize
};
