#!/usr/bin/env bash
# Execute cross-chain transfer test

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi


log_info "=== Cross-Chain Transfer Test ==="

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
CHAIN138_RPC="${RPC_URL:-https://rpc.d-bis.org}"
PRIVATE_KEY="${PRIVATE_KEY}"
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    PRIVATE_KEY="0x$PRIVATE_KEY"
fi

WETH9_MAINNET=$(grep "CCIPWETH9_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-0x000000000000008a}"

if [ -z "$WETH9_MAINNET" ]; then
    log_warn "⚠️  WETH9 Bridge address not found"
    exit 1
fi

echo "Test Configuration:"
echo "  Bridge: $WETH9_MAINNET"
echo "  WETH9: $WETH9_ADDRESS"
echo "  Destination Chain: Chain-138 ($CHAIN138_SELECTOR)"

# Get test amount (0.001 WETH = 1000000000000000 wei)
TEST_AMOUNT="1000000000000000"
TEST_RECIPIENT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")

if [ -z "$TEST_RECIPIENT" ]; then
    log_warn "⚠️  Could not derive recipient address"
    exit 1
fi

echo "Test Parameters:"
echo "  Amount: 0.001 WETH"
echo "  Recipient: $TEST_RECIPIENT"
log_warn "⚠️  This is a test transaction - ensure you have:"
echo "  1. WETH9 tokens approved for bridge"
echo "  2. Sufficient LINK for CCIP fees"
echo "  3. Bridge destinations configured"
read -p "Continue with test? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Test cancelled"
    exit 0
fi

echo "Executing test transfer..."
echo "  Approving WETH9..."
cast send "$WETH9_ADDRESS" "approve(address,uint256)" "$WETH9_MAINNET" "$TEST_AMOUNT" --rpc-url "$MAINNET_RPC" --private-key "$PRIVATE_KEY" --legacy 2>&1 | grep -E "Success|Transaction|error" | head -3

echo "  Initiating cross-chain transfer..."
cast send "$WETH9_MAINNET" "sendCrossChain(uint64,address,uint256)" "$CHAIN138_SELECTOR" "$TEST_RECIPIENT" "$TEST_AMOUNT" --rpc-url "$MAINNET_RPC" --private-key "$PRIVATE_KEY" --legacy 2>&1 | grep -E "Success|Transaction|error" | head -5

log_success "✅ Test transaction submitted"
echo "Monitor on Etherscan for transaction status"
