#!/bin/bash
# Complete setup script for tiered architecture

set -e

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

echo "=== DBIS Explorer Tiered Architecture Setup ==="
echo ""

# Step 1: Run database migration
echo "Step 1: Running database migration..."
bash "$SCRIPT_DIR/run-migration-0010.sh"
echo ""

# Step 2: Check environment variables
echo "Step 2: Checking environment variables..."
echo ""

REQUIRED_VARS=("DB_HOST" "DB_USER" "DB_PASSWORD" "DB_NAME")
MISSING_VARS=()

for var in "${REQUIRED_VARS[@]}"; do
    if [ -z "${!var}" ]; then
        MISSING_VARS+=("$var")
    fi
done

if [ ${#MISSING_VARS[@]} -gt 0 ]; then
    echo "⚠️  Missing environment variables:"
    for var in "${MISSING_VARS[@]}"; do
        echo "   - $var"
    done
    echo ""
    echo "Please set these in your environment or .env file"
    echo ""
else
    echo "✅ All required database variables are set"
fi

# Check optional variables
if [ -z "$JWT_SECRET" ]; then
    echo "⚠️  JWT_SECRET not set - using default (NOT SECURE FOR PRODUCTION)"
    echo "   Set JWT_SECRET environment variable with a strong random secret"
fi

if [ -z "$RPC_URL" ]; then
    echo "⚠️  RPC_URL not set - Track 1 RPC gateway will need configuration"
    echo "   Set RPC_URL environment variable (e.g., http://192.168.11.250:8545)"
fi

echo ""

# Step 3: Verify Go dependencies
echo "Step 3: Verifying Go dependencies..."
cd "$PROJECT_ROOT/backend"
if go mod tidy; then
    echo "✅ Go dependencies verified"
else
    echo "❌ Failed to verify Go dependencies"
    exit 1
fi
echo ""

# Step 4: Build backend
echo "Step 4: Building backend..."
if go build -o bin/api-server ./api/rest/cmd; then
    echo "✅ Backend built successfully"
else
    echo "❌ Failed to build backend"
    exit 1
fi
echo ""

# Step 5: Summary
echo "=== Setup Complete ==="
echo ""
echo "Next steps:"
echo "1. Set JWT_SECRET environment variable (required for production)"
echo "2. Set RPC_URL environment variable for Track 1 RPC gateway"
echo "3. Start the API server: ./bin/api-server"
echo "4. Approve users for Track 2-4 using the role management API"
echo "5. Add IP addresses to whitelist for Track 4 operators"
echo "6. Start Track 2 indexers to populate indexed data"
echo ""
echo "For more information, see: docs/TIERED_ARCHITECTURE_IMPLEMENTATION.md"
echo ""
