#!/bin/bash
# Complete deployment - execute this file

set -e

cd "$(dirname "$0")"

echo "=== Complete Deployment Execution ==="
echo ""

# Database credentials. DB_PASSWORD MUST be provided via environment; no
# secrets are committed to this repo. See docs/SECURITY.md.
: "${DB_PASSWORD:?DB_PASSWORD is required (export it before running this script)}"
export DB_PASSWORD
export DB_HOST="${DB_HOST:-localhost}"
export DB_USER="${DB_USER:-explorer}"
export DB_NAME="${DB_NAME:-explorer}"

# Step 1: Test database
echo "Step 1: Testing database connection..."
export PGPASSWORD="$DB_PASSWORD"
if psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" > /dev/null 2>&1; then
    echo "✅ Database connected"
else
    echo "❌ Database connection failed"
    exit 1
fi

# Step 2: Check tables
echo "Step 2: Checking tables..."
TABLE_COUNT=$(psql -h "$DB_HOST" -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 tables"

# Step 3: Run migration
if [ "$TABLE_COUNT" -lt "4" ]; then
    echo "Step 3: Running migration..."
    psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -f backend/database/migrations/0010_track_schema.up.sql > /dev/null 2>&1
    echo "✅ Migration complete"
else
    echo "Step 3: Migration already done"
fi

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

# Step 5: Start server
echo "Step 5: Starting server..."
cd backend
export JWT_SECRET="deployment-secret-$(date +%s)"
export 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

sleep 3

# Step 6: Test
echo "Step 6: Testing endpoints..."
if curl -s http://localhost:8080/health > /dev/null; then
    echo "✅ Server running (PID: $SERVER_PID)"
else
    echo "❌ Server failed to start"
    tail -20 logs/api-server.log
    exit 1
fi

echo ""
echo "=== Deployment Complete ==="
echo "Server PID: $SERVER_PID"
echo "Port: 8080"
echo "Logs: backend/logs/api-server.log"
echo ""
echo "Test: curl http://localhost:8080/health"

unset PGPASSWORD

