#!/usr/bin/env bash
# Test deployed contracts on all chains
# This script performs basic tests on deployed contracts

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"

source .env 2>/dev/null || true

echo "=== Testing Deployed Contracts ==="
echo ""

# Test function
test_chain() {
    local chain_name=$1
    local rpc_url=$2
    local weth9=$3
    local weth10=$4
    local bridge9=$5
    local bridge10=$6
    
    echo "Testing ${chain_name}..."
    echo "  RPC: ${rpc_url}"
    echo "  WETH9: ${weth9}"
    echo "  WETH10: ${weth10}"
    echo "  Bridge9: ${bridge9}"
    echo "  Bridge10: ${bridge10}"
    
    # Check if contracts exist
    if cast code "$weth9" --rpc-url "$rpc_url" > /dev/null 2>&1; then
        echo "  ✓ WETH9 contract exists"
    else
        echo "  ✗ WETH9 contract not found"
    fi
    
    if cast code "$weth10" --rpc-url "$rpc_url" > /dev/null 2>&1; then
        echo "  ✓ WETH10 contract exists"
    else
        echo "  ✗ WETH10 contract not found"
    fi
    
    if cast code "$bridge9" --rpc-url "$rpc_url" > /dev/null 2>&1; then
        echo "  ✓ CCIPWETH9Bridge contract exists"
    else
        echo "  ✗ CCIPWETH9Bridge contract not found"
    fi
    
    if cast code "$bridge10" --rpc-url "$rpc_url" > /dev/null 2>&1; then
        echo "  ✓ CCIPWETH10Bridge contract exists"
    else
        echo "  ✗ CCIPWETH10Bridge contract not found"
    fi
    
    echo ""
}

# Test all deployed chains
if [ -n "${WETH9_BSC:-}" ] && [ -n "${BSC_RPC_URL:-}" ]; then
    test_chain "BSC" "$BSC_RPC_URL" "$WETH9_BSC" "$WETH10_BSC" "$CCIPWETH9BRIDGE_BSC" "$CCIPWETH10BRIDGE_BSC"
fi

if [ -n "${WETH9_POLYGON:-}" ] && [ -n "${POLYGON_RPC_URL:-}" ]; then
    test_chain "Polygon" "$POLYGON_RPC_URL" "$WETH9_POLYGON" "$WETH10_POLYGON" "$CCIPWETH9BRIDGE_POLYGON" "$CCIPWETH10BRIDGE_POLYGON"
fi

if [ -n "${WETH9_AVALANCHE:-}" ] && [ -n "${AVALANCHE_RPC_URL:-}" ]; then
    test_chain "Avalanche" "$AVALANCHE_RPC_URL" "$WETH9_AVALANCHE" "$WETH10_AVALANCHE" "$CCIPWETH9BRIDGE_AVALANCHE" "$CCIPWETH10BRIDGE_AVALANCHE"
fi

if [ -n "${WETH9_BASE:-}" ] && [ -n "${BASE_RPC_URL:-}" ]; then
    test_chain "Base" "$BASE_RPC_URL" "$WETH9_BASE" "$WETH10_BASE" "$CCIPWETH9BRIDGE_BASE" "$CCIPWETH10BRIDGE_BASE"
fi

if [ -n "${WETH9_ARBITRUM:-}" ] && [ -n "${ARBITRUM_RPC_URL:-}" ]; then
    test_chain "Arbitrum" "$ARBITRUM_RPC_URL" "$WETH9_ARBITRUM" "$WETH10_ARBITRUM" "$CCIPWETH9BRIDGE_ARBITRUM" "$CCIPWETH10BRIDGE_ARBITRUM"
fi

if [ -n "${WETH9_OPTIMISM:-}" ] && [ -n "${OPTIMISM_RPC_URL:-}" ]; then
    test_chain "Optimism" "$OPTIMISM_RPC_URL" "$WETH9_OPTIMISM" "$WETH10_OPTIMISM" "$CCIPWETH9BRIDGE_OPTIMISM" "$CCIPWETH10BRIDGE_OPTIMISM"
fi

echo "=== Testing Complete ==="
