function requireAdminAuth(req, res, next) {
  const adminKey = process.env.ADMIN_API_KEY;

  if (!adminKey) {
    console.error('ADMIN_API_KEY is not configured');
    return res.status(500).json({
      error: 'Admin API key not configured',
    });
  }

  // Get the API key from Authorization header or query param
  const authHeader = req.get('Authorization') || '';
  const queryKey = req.query.key;
  const providedKey = authHeader.replace(/^Bearer\s+/i, '') || queryKey;

  if (!providedKey) {
    return res.status(401).json({
      error: 'Missing API key',
      message: 'Authorization header with Bearer token or ?key parameter is required',
    });
  }

  // Never expose the actual key in logs
  if (providedKey !== adminKey) {
    console.warn('Failed admin authentication attempt from IP:', req.ip);
    return res.status(403).json({
      error: 'Invalid API key',
      message: 'The provided API key is invalid',
    });
  }

  // Mark request as authenticated
  req.isAdmin = true;
  next();
}

/**
 * Optional admin auth middleware
 * Allows requests to proceed but marks if authenticated
 */
function optionalAdminAuth(req, res, next) {
  const adminKey = process.env.ADMIN_API_KEY;

  if (!adminKey) {
    req.isAdmin = false;
    return next();
  }

  const authHeader = req.get('Authorization') || '';
  const queryKey = req.query.key;
  const providedKey = authHeader.replace(/^Bearer\s+/i, '') || queryKey;

  if (providedKey && providedKey === adminKey) {
    req.isAdmin = true;
  } else {
    req.isAdmin = false;
  }

  next();
}

module.exports = {
  requireAdminAuth,
  optionalAdminAuth,
};

