#!/bin/bash
# Run all deployment steps

set -euo pipefail

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

echo "=== Running All Deployment Steps ==="
echo ""

# Database credentials
export DB_HOST="${DB_HOST:-localhost}"
export DB_PORT="${DB_PORT:-5432}"
export DB_USER="${DB_USER:-explorer}"
export DB_NAME="${DB_NAME:-explorer}"
if [ -z "${DB_PASSWORD:-}" ]; then
    echo "❌ DB_PASSWORD is required"
    echo "   Export DB_PASSWORD before running this script."
    exit 1
fi

extract_error_message() {
    local body="${1:-}"
    if [ -z "$body" ]; then
        return 0
    fi
    echo "$body" | jq -r '.error.message // empty' 2>/dev/null || true
}

# Step 1: Test database connection
echo "Step 1: Testing database connection..."
export PGPASSWORD="$DB_PASSWORD"
if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" > /dev/null 2>&1; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed"
    echo "Please verify PostgreSQL is running and credentials are correct"
    exit 1
fi
echo ""

# Step 2: Check existing tables
echo "Step 2: Checking for existing tables..."
TABLE_COUNT=$(psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('wallet_nonces', 'operator_roles', 'addresses', 'token_transfers');" -t 2>/dev/null | tr -d ' ')
echo "Found $TABLE_COUNT/4 track schema tables"
echo ""

# Step 3: Run migration if needed
if [ "$TABLE_COUNT" -lt "4" ]; then
    echo "Step 3: Running database migration..."
    if bash "$SCRIPT_DIR/run-migration-0010.sh" > /dev/null; then
        echo "✅ Migration completed"
    else
        echo "❌ Migration failed"
        exit 1
    fi
else
    echo "Step 3: Migration already complete (tables exist)"
fi
echo ""

# Step 4: Stop existing server
echo "Step 4: Stopping existing server..."
pkill -f api-server 2>/dev/null || true
sleep 2
echo "✅ Server stopped"
echo ""

# Step 5: Start server with database
echo "Step 5: Starting API server with database..."
cd "$PROJECT_ROOT/backend"

export JWT_SECRET="${JWT_SECRET:-deployment-secret-$(date +%s)}"
export RPC_URL="${RPC_URL:-http://192.168.11.250:8545}"
export CHAIN_ID=138
export PORT=8080

mkdir -p logs

nohup ./bin/api-server > logs/api-server.log 2>&1 &
SERVER_PID=$!
echo $SERVER_PID > logs/api-server.pid

# Wait for server to start
echo "Waiting for server to start..."
for i in {1..10}; do
    if curl -s http://localhost:8080/health > /dev/null 2>&1; then
        echo "✅ Server started (PID: $SERVER_PID)"
        break
    fi
    if [ $i -eq 10 ]; then
        echo "❌ Server failed to start"
        tail -20 logs/api-server.log
        exit 1
    fi
    sleep 1
done
echo ""

# Step 6: Test endpoints
echo "Step 6: Testing endpoints..."

echo -n "  Health endpoint... "
if curl -s http://localhost:8080/health | grep -q "healthy\|degraded"; then
    echo "✅"
else
    echo "⚠️"
fi

echo -n "  Feature flags... "
if curl -s http://localhost:8080/api/v1/features | grep -q "track"; then
    echo "✅"
else
    echo "⚠️"
fi

echo -n "  Track 1 blocks... "
HTTP_CODE=$(curl -s -w "%{http_code}" -o /dev/null "http://localhost:8080/api/v1/track1/blocks/latest?limit=1")
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅"
else
    echo "⚠️ (HTTP $HTTP_CODE)"
fi

echo -n "  Auth nonce... "
NONCE_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "http://localhost:8080/api/v1/auth/nonce" \
    -H 'Content-Type: application/json' \
    -d '{"address":"0x1234567890123456789012345678901234567890"}')
NONCE_CODE=$(echo "$NONCE_RESPONSE" | tail -n1)
NONCE_BODY=$(echo "$NONCE_RESPONSE" | sed '$d')
NONCE_ERROR=$(extract_error_message "$NONCE_BODY")
if [ "$NONCE_CODE" = "200" ]; then
    echo "✅"
else
    echo "❌ (HTTP $NONCE_CODE)"
    if [ -n "$NONCE_ERROR" ]; then
        echo "     $NONCE_ERROR"
    fi
    echo "     Wallet auth is not healthy; stop here until migration and DB access are fixed."
    exit 1
fi

echo -n "  Track 2 auth check... "
TRACK2_CODE=$(curl -s -w "%{http_code}" -o /dev/null "http://localhost:8080/api/v1/track2/search?q=test")
if [ "$TRACK2_CODE" = "401" ]; then
    echo "✅ (correctly requires auth)"
else
    echo "⚠️ (HTTP $TRACK2_CODE)"
fi

echo ""

# Step 7: Summary
echo "=== Deployment Complete ==="
echo ""
echo "✅ Database: Connected"
echo "✅ Migration: Complete"
echo "✅ Server: Running (PID: $SERVER_PID)"
echo "✅ Endpoints: Tested"
echo ""
echo "Server Information:"
echo "  PID: $SERVER_PID"
echo "  Port: 8080"
echo "  Logs: $PROJECT_ROOT/backend/logs/api-server.log"
echo ""
echo "Test Commands:"
echo "  curl http://localhost:8080/health"
echo "  curl http://localhost:8080/api/v1/features"
echo "  curl http://localhost:8080/api/v1/track1/blocks/latest?limit=5"
echo ""
echo "Next Steps:"
echo "  1. Test authentication flow"
echo "  2. Approve users: bash scripts/approve-user.sh <address> <track>"
echo "  3. Monitor: tail -f backend/logs/api-server.log"
echo ""

unset PGPASSWORD
