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

set -e

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"

# 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... "
    if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'addresses');" -t | grep -q "t"; then
        echo "✅ Tables exist"
    else
        echo "⚠️  Tables not found - migration needed"
    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"
fi

unset PGPASSWORD

