#!/usr/bin/env bash
# Test RPC endpoints for Thirdweb
# Usage: ./scripts/test-rpc-thirdweb.sh

set -euo pipefail

RPC_URL="https://rpc.public-0138.defi-oracle.io"

echo "Testing RPC Endpoint: $RPC_URL"
echo "=================================="
echo ""

# Test 1: Chain ID
echo "Test 1: Get Chain ID"
RESPONSE=$(curl -k -s -X POST "$RPC_URL" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}')

if echo "$RESPONSE" | jq -e '.result == "0x8a"' >/dev/null 2>&1; then
    echo "✅ Chain ID: $(echo "$RESPONSE" | jq -r '.result')"
else
    echo "❌ Chain ID test failed"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
fi
echo ""

# Test 2: Block Number
echo "Test 2: Get Latest Block Number"
RESPONSE=$(curl -k -s -X POST "$RPC_URL" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":2}')

if echo "$RESPONSE" | jq -e '.result' >/dev/null 2>&1; then
    BLOCK_HEX=$(echo "$RESPONSE" | jq -r '.result')
    BLOCK_DEC=$((16#${BLOCK_HEX#0x}))
    echo "✅ Latest Block: $BLOCK_DEC ($BLOCK_HEX)"
else
    echo "❌ Block number test failed"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
fi
echo ""

# Test 3: Network ID
echo "Test 3: Get Network ID"
RESPONSE=$(curl -k -s -X POST "$RPC_URL" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","method":"net_version","params":[],"id":3}')

if echo "$RESPONSE" | jq -e '.result == "138"' >/dev/null 2>&1; then
    echo "✅ Network ID: $(echo "$RESPONSE" | jq -r '.result')"
else
    echo "❌ Network ID test failed"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
fi
echo ""

# Test 4: CORS Headers
echo "Test 4: Check CORS Headers"
CORS_HEADERS=$(curl -k -s -I -X OPTIONS "$RPC_URL" \
  -H 'Origin: https://thirdweb.com' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: Content-Type' 2>&1 | grep -i "access-control" || echo "")

if echo "$CORS_HEADERS" | grep -qi "access-control-allow-origin"; then
    echo "✅ CORS headers present"
    echo "$CORS_HEADERS"
else
    echo "⚠️  CORS headers not found (may still work)"
fi
echo ""

echo "=================================="
echo "RPC Endpoint Tests Complete"
echo ""
