#!/bin/bash
# Fix database connection and run migration

set -e

echo "=== Database Connection Fix ==="
echo ""

# Database credentials for custom explorer backend
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-L@ker\$2010}"
DB_NAME="${DB_NAME:-explorer}"

echo "Testing connection with:"
echo "  Host: $DB_HOST:$DB_PORT"
echo "  User: $DB_USER"
echo "  Database: $DB_NAME"
echo ""

export PGPASSWORD="$DB_PASSWORD"

# Test connection
echo -n "Testing connection... "
if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" > /dev/null 2>&1; then
    echo "✅ Connected"
    
    # Check if migration tables exist
    echo -n "Checking for track schema 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 ' ')
    
    if [ "$TABLE_COUNT" -ge "4" ]; then
        echo "✅ All tables exist ($TABLE_COUNT/4)"
        echo ""
        echo "✅ Database is ready!"
    else
        echo "⚠️  Tables missing ($TABLE_COUNT/4 found)"
        echo ""
        echo "Running migration..."
        
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
        MIGRATION_FILE="$PROJECT_ROOT/backend/database/migrations/0010_track_schema.up.sql"
        
        if [ -f "$MIGRATION_FILE" ]; then
            if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f "$MIGRATION_FILE" 2>&1 | tail -10; then
                echo ""
                echo "✅ Migration completed"
            else
                echo ""
                echo "⚠️  Migration may have partially completed or tables already exist"
            fi
        else
            echo "❌ Migration file not found: $MIGRATION_FILE"
        fi
    fi
else
    echo "❌ Connection failed"
    echo ""
    echo "Troubleshooting:"
    echo "1. Verify PostgreSQL is running: systemctl status postgresql"
    echo "2. Check if user exists:"
    echo "   PGPASSWORD='postgres-password' psql -h $DB_HOST -U postgres -c '\du'"
    echo "3. Check if database exists:"
    echo "   PGPASSWORD='postgres-password' psql -h $DB_HOST -U postgres -c '\l'"
    echo "4. Verify password is correct"
    echo ""
    echo "Note: Custom explorer backend uses 'explorer' user, not 'blockscout'"
    exit 1
fi

unset PGPASSWORD

echo ""
echo "=== Next Steps ==="
echo "1. Restart API server with database password:"
echo "   export DB_PASSWORD='$DB_PASSWORD'"
echo "   cd backend && ./bin/api-server"
echo ""
echo "2. Test health endpoint:"
echo "   curl http://localhost:8080/health"
echo ""

