#!/bin/bash

# Script to fix database password for explorer backend
# This script must be run with sudo privileges to reset the PostgreSQL password

set -euo pipefail

cd "$(dirname "$0")/.."

# Default configuration
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-changeme}"
DB_NAME="${DB_NAME:-explorer}"

echo "=========================================="
echo "Database Password Fix Script"
echo "=========================================="
echo ""
echo "This script will:"
echo "  1. Create or update the 'explorer' PostgreSQL user with password 'changeme'"
echo "  2. Create the 'explorer' database if it doesn't exist"
echo "  3. Grant all privileges to the explorer user"
echo ""
echo "Configuration:"
echo "  User: $DB_USER"
echo "  Password: $DB_PASSWORD"
echo "  Database: $DB_NAME"
echo ""

# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then
    echo "⚠️  This script requires sudo privileges to modify PostgreSQL."
    echo ""
    echo "Please run this script with sudo:"
    echo "  sudo ./scripts/fix-database-password-manual.sh"
    echo ""
    exit 1
fi

# Check if PostgreSQL is running
echo -n "Checking PostgreSQL... "
if systemctl is-active --quiet postgresql || pg_isready >/dev/null 2>&1; then
    echo "✅ PostgreSQL is running"
else
    echo "❌ PostgreSQL is not running"
    echo "Please start PostgreSQL first:"
    echo "  sudo systemctl start postgresql"
    exit 1
fi

# Create or update user
echo ""
echo "Creating/updating PostgreSQL user '$DB_USER'..."
sudo -u postgres psql -c "DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_user WHERE usename = '$DB_USER') THEN
        CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
        RAISE NOTICE 'User $DB_USER created';
    ELSE
        ALTER USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
        RAISE NOTICE 'User $DB_USER password updated';
    END IF;
END
\$\$;" 2>&1

# Create database
echo ""
echo "Creating database '$DB_NAME'..."
sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname = '$DB_NAME'" | grep -q 1 || \
    sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;" 2>&1

# Grant privileges
echo ""
echo "Granting privileges..."
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" 2>&1

# Test connection
echo ""
echo -n "Testing database connection... "
if PGPASSWORD="$DB_PASSWORD" psql -h localhost -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" >/dev/null 2>&1; then
    echo "✅ Connection successful!"
    echo ""
    echo "=========================================="
    echo "✅ Database password has been fixed!"
    echo "=========================================="
    echo ""
    echo "Next steps:"
    echo "1. Restart the backend service:"
    echo "   kill \$(cat /tmp/explorer_backend.pid) 2>/dev/null; ./scripts/start-backend-service.sh"
    echo ""
    echo "2. Verify the connection:"
    echo "   curl http://localhost:8080/health"
    echo ""
    exit 0
else
    echo "❌ Connection still failing"
    echo ""
    echo "Please check:"
    echo "  1. PostgreSQL is running: sudo systemctl status postgresql"
    echo "  2. User exists: sudo -u postgres psql -c '\\du'"
    echo "  3. Database exists: sudo -u postgres psql -c '\\l'"
    exit 1
fi

