/**
 * Admin authentication middleware to protect admin routes
 */
module.exports = (pool, query) => {
    return async (req, res, next) => {
      // Get API key from header
      const apiKey = req.headers['x-api-key'];
      
      if (!apiKey) {
        return res.status(401).json({
          error: true,
          message: 'API key is required'
        });
      }
      
      try {
        // Verify API key and check admin status
        const result = await query(
          'SELECT id, email, first_name, last_name, is_admin FROM users WHERE api_key = $1',
          [apiKey]
        );
        
        if (result.rows.length === 0) {
          return res.status(401).json({
            error: true,
            message: 'Invalid API key'
          });
        }
        
        
        if (!result.rows[0].is_admin) {
          return res.status(403).json({
            error: true,
            message: 'Admin access required'
          });
        }
        
        // Add user to request object
        req.user = result.rows[0];
        
        next();
      } catch (error) {
        return res.status(500).json({
          error: true,
          message: 'Error authenticating user'
        });
      }
    };
  };