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

set -euo pipefail

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

# Database credentials for the selected deployment mode
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
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

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

export PGPASSWORD="$DB_PASSWORD"

sql_scalar() {
    local sql="$1"
    psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -Atc "$sql" 2>/dev/null | tr -d ' '
}

is_shared_blockscout_db() {
    sql_scalar "
        SELECT CASE
            WHEN EXISTS (
                SELECT 1
                FROM information_schema.tables
                WHERE table_schema = 'public' AND table_name = 'addresses'
            ) AND NOT EXISTS (
                SELECT 1
                FROM information_schema.columns
                WHERE table_schema = 'public' AND table_name = 'addresses' AND column_name = 'address'
            )
            THEN 'yes'
            ELSE 'no'
        END;
    "
}

# 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"

    if [ "$(is_shared_blockscout_db || echo no)" = "yes" ]; then
        echo "Mode: shared Blockscout DB detected"
        REQUIRED_TABLES=(operator_events operator_ip_whitelist operator_roles wallet_nonces)
    else
        echo "Mode: standalone explorer DB detected"
        REQUIRED_TABLES=(wallet_nonces operator_roles addresses token_transfers)
    fi

    echo -n "Checking required tables... "
    table_list=""
    for table in "${REQUIRED_TABLES[@]}"; do
        if [ -n "$table_list" ]; then
            table_list+=", "
        fi
        table_list+="'$table'"
    done
    TABLE_COUNT=$(sql_scalar "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN (${table_list});")

    if [ "${TABLE_COUNT:-0}" -ge "${#REQUIRED_TABLES[@]}" ]; then
        echo "✅ All required tables exist (${TABLE_COUNT}/${#REQUIRED_TABLES[@]})"
        echo ""
        echo "✅ Database is ready!"
    else
        echo "⚠️  Tables missing (${TABLE_COUNT:-0}/${#REQUIRED_TABLES[@]} found)"
        echo ""
        echo "Running migration..."
        
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

        if [ -f "$PROJECT_ROOT/scripts/run-migration-0010.sh" ]; then
            if DB_HOST="$DB_HOST" DB_PORT="$DB_PORT" DB_USER="$DB_USER" DB_PASSWORD="$DB_PASSWORD" DB_NAME="$DB_NAME" \
                bash "$PROJECT_ROOT/scripts/run-migration-0010.sh"; then
                echo ""
                echo "✅ Migration completed"
            else
                echo ""
                echo "❌ Migration failed"
                exit 1
            fi
        else
            echo "❌ Migration helper not found: $PROJECT_ROOT/scripts/run-migration-0010.sh"
            exit 1
        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 "Use the credentials for your deployment mode:"
    echo "  - standalone explorer DB: explorer / explorer"
    echo "  - shared Blockscout DB: blockscout / blockscout"
    exit 1
fi

unset PGPASSWORD

echo ""
echo "=== Next Steps ==="
echo "1. Restart API server with database password:"
echo "   export DB_PASSWORD='<your explorer DB password>'"
echo "   # Set DB_USER / DB_NAME too if you are using the shared Blockscout DB"
echo "   cd backend && ./bin/api-server"
echo ""
echo "2. Test health endpoint:"
echo "   curl http://localhost:8080/health"
echo ""
