#!/bin/bash
# Check database connection and credentials

set -euo pipefail

DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-changeme}"
DB_NAME="${DB_NAME:-explorer}"

echo "=== Database Connection Check ==="
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=(addresses token_transfers wallet_nonces operator_roles)
    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 "✅ Ready (${TABLE_COUNT}/${#REQUIRED_TABLES[@]})"
    else
        echo "⚠️  Missing tables (${TABLE_COUNT:-0}/${#REQUIRED_TABLES[@]}) - run bash scripts/run-migration-0010.sh"
    fi
else
    echo "❌ Connection failed"
    echo ""
    echo "Troubleshooting:"
    echo "1. Check if PostgreSQL is running: systemctl status postgresql"
    echo "2. Verify credentials in database config"
    echo "3. Check pg_hba.conf for authentication method"
    echo "4. Try connecting manually: psql -h $DB_HOST -U $DB_USER -d $DB_NAME"
    echo ""
    echo "Use the credentials for your deployment mode:"
    echo "  - standalone explorer DB: explorer / explorer"
    echo "  - shared Blockscout DB: blockscout / blockscout"
fi

unset PGPASSWORD
