#!/usr/bin/env bash
# Smoke test for the EZ-Input payments plugin.
# Assumes the FastAPI host is running on :8900, or starts it from the backend venv.
set -euo pipefail

BASE_URL="${EZ_PAYMENTS_URL:-http://127.0.0.1:8900}"
USER_ID="${EZ_PAYMENTS_USER:-test-user-$$}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKEND_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

SERVER_PID=""
STOP_SERVER=0

cleanup() {
    if [ "$STOP_SERVER" = "1" ] && [ -n "$SERVER_PID" ]; then
        echo "Stopping temporary server (pid $SERVER_PID)..."
        kill "$SERVER_PID" 2>/dev/null || true
        wait "$SERVER_PID" 2>/dev/null || true
    fi
}
trap cleanup EXIT

if ! curl -sf "$BASE_URL/health" >/dev/null 2>&1; then
    echo "No server on $BASE_URL; starting temporary instance..."
    cd "$BACKEND_DIR"
    # shellcheck source=/dev/null
    source .venv/bin/activate
    nohup python fastapi_integration.py >/tmp/ez_payments_test_server.log 2>&1 &
    SERVER_PID=$!
    for _ in $(seq 1 30); do
        curl -sf "$BASE_URL/health" >/dev/null 2>&1 && break
        sleep 1
    done
    curl -sf "$BASE_URL/health" >/dev/null 2>&1 || {
        echo "Server failed to start. Log:"
        cat /tmp/ez_payments_test_server.log
        exit 1
    }
    STOP_SERVER=1
    echo "Server started on $BASE_URL (pid $SERVER_PID)"
fi

jget() {
    python3 -c "import json; print(json.load(open('/tmp/resp.json'))$1)"
}

http_get() {
    local url=$1 name=$2
    local code
    code=$(curl -s -o /tmp/resp.json -w "%{http_code}" "$url")
    if [ "$code" != "200" ]; then
        echo "FAIL $name (HTTP $code)"
        cat /tmp/resp.json
        exit 1
    fi
    echo "PASS $name"
}

http_post() {
    local url=$1 name=$2 body=$3
    local code
    code=$(curl -s -o /tmp/resp.json -w "%{http_code}" \
        -X POST "$url" \
        -H "Content-Type: application/json" \
        -d "$body")
    if [ "$code" != "200" ]; then
        echo "FAIL $name (HTTP $code)"
        cat /tmp/resp.json
        exit 1
    fi
    echo "PASS $name"
}

echo "=== Testing /payments/rate ==="
http_get "$BASE_URL/payments/rate" "rate"
RATE_USD_PER_ERC=$(jget "['usd_per_erc']")
RATE_ERC_PER_USD=$(jget "['erc_per_usd']")
echo "  usd_per_erc=$RATE_USD_PER_ERC  erc_per_usd=$RATE_ERC_PER_USD"

echo "=== Testing checkout methods ==="
for method in stripe airwallex erc20; do
    http_post "$BASE_URL/payments/checkout" "checkout-$method" \
        "{\"product_id\":\"karma\",\"user_id\":\"$USER_ID\",\"currency\":\"usd\",\"method\":\"$method\"}"
    ORDER_ID=$(jget "['order_id']")
    STATUS=$(jget "['status']")
    echo "  order_id=$ORDER_ID status=$STATUS"

    if [ "$method" != "erc20" ]; then
        http_post "$BASE_URL/payments/webhook/$method" "webhook-$method-$ORDER_ID" "{}"
    fi

    if [ "$method" = "erc20" ]; then
        http_post "$BASE_URL/payments/erc20/verify" "erc20-verify-$ORDER_ID" \
            "{\"order_id\":\"$ORDER_ID\",\"tx_hash\":\"0xdeadbeef\"}"
    fi
done

echo "=== Testing /payments/wallet ==="
http_get "$BASE_URL/payments/wallet/$USER_ID" "wallet"
BALANCE=$(jget "['erc_balance']")
echo "  user=$USER_ID balance=$BALANCE"

echo "=== Testing /payments/credits/use ==="
http_post "$BASE_URL/payments/credits/use" "credits-use" \
    "{\"user_id\":\"$USER_ID\",\"amount\":1,\"reason\":\"smoke-test\"}"
REMAINING=$(jget "['remaining_balance']")
echo "  remaining_balance=$REMAINING"

echo ""
echo "All payment smoke tests passed."
