#!/usr/bin/env bash
# Test thirdweb Bridge API with proper authentication and format
# Usage: THIRDWEB_SECRET_KEY=your_key ./test-thirdweb-bridge-with-auth.sh

set -euo pipefail

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

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_section() { echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"; echo -e "${CYAN}$1${NC}"; echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"; }

# Configuration
THIRDWEB_SECRET_KEY="${THIRDWEB_SECRET_KEY:-}"
CHAIN138_ID=138
ETHEREUM_MAINNET_ID=1
WETH_CANONICAL="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
USDT_MAINNET="0xdAC17F958D2ee523a2206206994597C13D831ec7"
AMOUNT="1000000000000000000"  # 1 WETH
WALLET_ADDRESS="${WALLET_ADDRESS:-0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb}"  # Default test wallet

log_section "thirdweb Bridge API Test (With Authentication)"

# Check for API key
if [ -z "$THIRDWEB_SECRET_KEY" ]; then
    log_error "THIRDWEB_SECRET_KEY environment variable is required"
    log_info ""
    log_info "To get your API key:"
    log_info "  1. Sign up at https://thirdweb.com"
    log_info "  2. Go to Dashboard → Settings → API Keys"
    log_info "  3. Generate a secret key for Bridge API"
    log_info ""
    log_info "Usage:"
    log_info "  THIRDWEB_SECRET_KEY=your_key WALLET_ADDRESS=0x... ./test-thirdweb-bridge-with-auth.sh"
    exit 1
fi

if [ "$WALLET_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "WALLET_ADDRESS not set, using zero address (may cause errors)"
    log_info "Set WALLET_ADDRESS environment variable for proper testing"
fi

# Test 1: Check Supported Chains
log_section "Test 1: Check Supported Chains"

log_info "Checking if ChainID 138 is supported..."
CHAIN_RESPONSE=$(curl -s -X GET "https://api.thirdweb.com/v1/bridge/chains" \
    -H "x-secret-key: $THIRDWEB_SECRET_KEY" \
    --max-time 10 \
    2>&1 || echo "ERROR")

if [[ "$CHAIN_RESPONSE" == *"ERROR"* ]] || [[ "$CHAIN_RESPONSE" == *"401"* ]] || [[ "$CHAIN_RESPONSE" == *"Unauthorized"* ]]; then
    log_error "Failed to get supported chains"
    log_error "Response: $CHAIN_RESPONSE"
    log_warn "Check your API key and try again"
    exit 1
fi

if command -v jq &> /dev/null; then
    CHAIN138_SUPPORTED=$(echo "$CHAIN_RESPONSE" | jq -r '.[] | select(.chainId == 138) | .chainId' 2>/dev/null || echo "")
    if [ -n "$CHAIN138_SUPPORTED" ]; then
        log_success "✅ ChainID 138 is supported!"
        echo "$CHAIN_RESPONSE" | jq '.[] | select(.chainId == 138)' 2>/dev/null || echo "$CHAIN_RESPONSE"
    else
        log_warn "⚠ ChainID 138 is NOT in the supported chains list"
        log_info "Supported chains:"
        echo "$CHAIN_RESPONSE" | jq -r '.[] | "\(.chainId) - \(.name)"' 2>/dev/null || echo "$CHAIN_RESPONSE"
        log_warn "You may need to request ChainID 138 support from thirdweb"
    fi
else
    log_warn "jq not available, cannot parse response"
    log_info "Response: $CHAIN_RESPONSE"
fi

# Test 2: Check Supported Tokens
log_section "Test 2: Check Supported Tokens on ChainID 138"

log_info "Checking if WETH is recognized on ChainID 138..."
TOKEN_RESPONSE=$(curl -s -X GET "https://api.thirdweb.com/v1/bridge/tokens?chainId=$CHAIN138_ID" \
    -H "x-secret-key: $THIRDWEB_SECRET_KEY" \
    --max-time 10 \
    2>&1 || echo "ERROR")

if [[ "$TOKEN_RESPONSE" != *"ERROR"* ]]; then
    if command -v jq &> /dev/null; then
        WETH_RECOGNIZED=$(echo "$TOKEN_RESPONSE" | jq -r ".[] | select(.address == \"$WETH_CANONICAL\") | .address" 2>/dev/null || echo "")
        if [ -n "$WETH_RECOGNIZED" ]; then
            log_success "✅ WETH is recognized at canonical address!"
            echo "$TOKEN_RESPONSE" | jq ".[] | select(.address == \"$WETH_CANONICAL)" 2>/dev/null || echo "$TOKEN_RESPONSE"
        else
            log_warn "⚠ WETH not found in supported tokens list"
            log_info "Supported tokens on ChainID 138:"
            echo "$TOKEN_RESPONSE" | jq -r '.[] | "\(.address) - \(.symbol // "N/A")"' 2>/dev/null || echo "$TOKEN_RESPONSE"
        fi
    else
        log_warn "jq not available, cannot parse response"
        log_info "Response: $TOKEN_RESPONSE"
    fi
else
    log_error "Failed to get supported tokens"
    log_error "Response: $TOKEN_RESPONSE"
fi

# Test 3: Get Bridge Quote
log_section "Test 3: Get Bridge Quote (Swap)"

log_info "Requesting bridge quote..."
log_info "  From: ChainID $CHAIN138_ID, WETH ($WETH_CANONICAL)"
log_info "  To: ChainID $ETHEREUM_MAINNET_ID, USDT ($USDT_MAINNET)"
log_info "  Amount: 1 WETH ($AMOUNT wei)"
log_info ""

SWAP_PAYLOAD=$(cat <<EOF
{
  "from": "$WALLET_ADDRESS",
  "exact": "input",
  "tokenIn": {
    "address": "$WETH_CANONICAL",
    "chainId": $CHAIN138_ID,
    "amount": "$AMOUNT"
  },
  "tokenOut": {
    "address": "$USDT_MAINNET",
    "chainId": $ETHEREUM_MAINNET_ID,
    "minAmount": "0"
  }
}
EOF
)

SWAP_RESPONSE=$(curl -s -X POST "https://api.thirdweb.com/v1/bridge/swap" \
    -H "Content-Type: application/json" \
    -H "x-secret-key: $THIRDWEB_SECRET_KEY" \
    -d "$SWAP_PAYLOAD" \
    --max-time 30 \
    2>&1 || echo "ERROR")

if [[ "$SWAP_RESPONSE" == *"ERROR"* ]] || [[ "$SWAP_RESPONSE" == *"401"* ]] || [[ "$SWAP_RESPONSE" == *"Unauthorized"* ]]; then
    log_error "Failed to get bridge quote"
    log_error "Response: $SWAP_RESPONSE"
    exit 1
fi

if command -v jq &> /dev/null; then
    # Check for errors
    if echo "$SWAP_RESPONSE" | jq -e '.error, .message' >/dev/null 2>&1; then
        ERROR_MSG=$(echo "$SWAP_RESPONSE" | jq -r '.error // .message // "Unknown error"' 2>/dev/null || echo "API error")
        log_error "API returned error: $ERROR_MSG"
        log_info "Full response:"
        echo "$SWAP_RESPONSE" | jq '.' 2>/dev/null || echo "$SWAP_RESPONSE"
    # Check for valid quote
    elif echo "$SWAP_RESPONSE" | jq -e '.quoteId, .estimatedTime, .fee, .toAmount' >/dev/null 2>&1; then
        log_success "✅ Valid bridge quote obtained!"
        log_info "Quote Details:"
        echo "$SWAP_RESPONSE" | jq '.' 2>/dev/null || echo "$SWAP_RESPONSE"
    else
        log_warn "Unexpected response format"
        log_info "Response:"
        echo "$SWAP_RESPONSE" | jq '.' 2>/dev/null || echo "$SWAP_RESPONSE"
    fi
else
    log_warn "jq not available, cannot parse response"
    log_info "Response: $SWAP_RESPONSE"
fi

# Summary
log_section "Test Summary"

log_info "Tests completed. Review results above to determine:"
log_info "  1. Is ChainID 138 supported?"
log_info "  2. Is WETH recognized?"
log_info "  3. Can we get a valid bridge quote?"
