#!/bin/bash

set -e

# Load test script for RPC endpoint

RPC_URL="${RPC_URL:-http://localhost:8545}"
REQUESTS="${REQUESTS:-1000}"
CONCURRENT="${CONCURRENT:-10}"

echo "Load Test for DeFi Oracle Meta Mainnet RPC"
echo "==========================================="
echo "RPC URL: $RPC_URL"
echo "Requests: $REQUESTS"
echo "Concurrent: $CONCURRENT"
echo ""

# Install dependencies if needed
if ! command -v ab &> /dev/null; then
    echo "Installing Apache Bench..."
    sudo apt-get update && sudo apt-get install -y apache2-utils
fi

# Create test payload
cat > /tmp/rpc-payload.json <<EOF
{
  "jsonrpc": "2.0",
  "method": "eth_blockNumber",
  "params": [],
  "id": 1
}
EOF

# Run load test
echo "Running load test..."
ab -n "$REQUESTS" -c "$CONCURRENT" -p /tmp/rpc-payload.json -T "application/json" "$RPC_URL" > /tmp/load-test-results.txt

# Parse results
REQUESTS_PER_SEC=$(grep "Requests per second" /tmp/load-test-results.txt | awk '{print $4}')
TIME_PER_REQUEST=$(grep "Time per request" /tmp/load-test-results.txt | head -1 | awk '{print $4}')
FAILED_REQUESTS=$(grep "Failed requests" /tmp/load-test-results.txt | awk '{print $3}')

echo "Results:"
echo "  Requests per second: $REQUESTS_PER_SEC"
echo "  Time per request: $TIME_PER_REQUEST ms"
echo "  Failed requests: $FAILED_REQUESTS"

# Check if test passed
if [ "$FAILED_REQUESTS" -gt 0 ]; then
    echo "❌ Load test failed: $FAILED_REQUESTS failed requests"
    exit 1
else
    echo "✅ Load test passed"
fi

# Cleanup
rm -f /tmp/rpc-payload.json /tmp/load-test-results.txt

