#!/bin/bash

# Emergency Database Recovery Script
# Use this if migrations fail or database gets corrupted

echo "🚨 Emergency Database Recovery"
echo "This script will help recover from database issues"

# Function to list available backups
list_backups() {
    echo "📋 Available database backups:"
    ls -la backup_*.sql 2>/dev/null || echo "No backups found"
}

# Function to restore from backup
restore_backup() {
    local backup_file=$1
    if [ -z "$backup_file" ]; then
        echo "❌ Please specify a backup file"
        list_backups
        return 1
    fi
    
    echo "🔄 Restoring from backup: $backup_file"
    mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME < $backup_file
    echo "✅ Database restored from backup"
}

# Function to reset migrations
reset_migrations() {
    echo "🔄 Resetting migration state..."
    
    # Mark all migrations as applied without running them
    npx prisma migrate resolve --applied "$(ls prisma/migrations | tail -1)"
    
    echo "✅ Migration state reset"
}

# Function to force schema sync
force_schema_sync() {
    echo "🔄 Force syncing schema to database..."
    
    # Push schema without creating migration
    npx prisma db push --force-reset
    
    echo "✅ Schema synced"
}

# Main menu
echo "Select recovery option:"
echo "1. List available backups"
echo "2. Restore from backup"
echo "3. Reset migration state"
echo "4. Force schema sync"
echo "5. Check current migration status"

read -p "Enter option (1-5): " option

case $option in
    1)
        list_backups
        ;;
    2)
        read -p "Enter backup filename: " backup_file
        restore_backup $backup_file
        ;;
    3)
        reset_migrations
        ;;
    4)
        force_schema_sync
        ;;
    5)
        npx prisma migrate status
        ;;
    *)
        echo "❌ Invalid option"
        ;;
esac 