#!/bin/bash
# Fix DATABASE_URL in .env file

ENV_FILE=".env"
BACKUP_FILE=".env.backup.$(date +%Y%m%d_%H%M%S)"

if [ ! -f "$ENV_FILE" ]; then
    echo "❌ .env file not found"
    exit 1
fi

# Backup original
cp "$ENV_FILE" "$BACKUP_FILE"
echo "✅ Backed up .env to $BACKUP_FILE"

# Check if DATABASE_URL needs fixing
if grep -q "DATABASE_URL=postgresql://user:password@host:port/database" "$ENV_FILE"; then
    echo "⚠️  Found placeholder DATABASE_URL. Please provide the correct connection string."
    echo ""
    echo "Expected format: postgresql://user:password@host:port/database"
    echo ""
    read -p "Enter database host [192.168.11.100]: " DB_HOST
    DB_HOST=${DB_HOST:-192.168.11.100}
    
    read -p "Enter database port [5432]: " DB_PORT
    DB_PORT=${DB_PORT:-5432}
    
    read -p "Enter database name [dbis_core]: " DB_NAME
    DB_NAME=${DB_NAME:-dbis_core}
    
    read -p "Enter database user [dbis]: " DB_USER
    DB_USER=${DB_USER:-dbis}
    
    read -sp "Enter database password: " DB_PASS
    echo ""
    
    # URL encode password (basic - handles most cases)
    DB_PASS_ENCODED=$(echo "$DB_PASS" | sed 's/:/%3A/g; s/@/%40/g; s/#/%23/g; s/\//%2F/g; s/\?/%3F/g; s/&/%26/g; s/=/%3D/g')
    
    NEW_URL="postgresql://${DB_USER}:${DB_PASS_ENCODED}@${DB_HOST}:${DB_PORT}/${DB_NAME}"
    
    # Replace the line
    sed -i "s|DATABASE_URL=.*|DATABASE_URL=${NEW_URL}|" "$ENV_FILE"
    
    echo "✅ DATABASE_URL updated in .env file"
    echo "   Connection: postgresql://${DB_USER}:***@${DB_HOST}:${DB_PORT}/${DB_NAME}"
else
    echo "✅ DATABASE_URL appears to be set (not a placeholder)"
    echo "   Current value: $(grep '^DATABASE_URL' "$ENV_FILE" | sed 's/:[^:@]*@/:***@/g')"
fi
