#!/bin/bash

# LuckyChit Database Restore Script

set -e

DB_NAME="luckychit"
DB_USER="luckychit"
DB_HOST="localhost"
BACKUP_DIR="/home/luckychit/backups"

echo "🗄️  LuckyChit Database Restore"
echo "==============================="
echo ""

if [ ! -d "$BACKUP_DIR" ]; then
    echo "❌ Backup directory not found: $BACKUP_DIR"
    exit 1
fi

echo "📦 Available backups:"
echo ""
ls -lh "$BACKUP_DIR"/luckychit_backup_*.sql.gz 2>/dev/null | nl || {
    echo "❌ No backup files found"
    exit 1
}

echo ""
echo "Enter the filename to restore (without path):"
read -r BACKUP_FILENAME

BACKUP_FILE="$BACKUP_DIR/$BACKUP_FILENAME"

if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ Backup file not found: $BACKUP_FILE"
    exit 1
fi

echo ""
echo "⚠️  WARNING: This will REPLACE the current database!"
echo "Database: $DB_NAME"
echo "Backup file: $BACKUP_FILE"
echo ""
echo "Are you sure? (yes/no)"
read -r CONFIRM

if [ "$CONFIRM" != "yes" ]; then
    echo "❌ Restore cancelled"
    exit 0
fi

# Safety backup
SAFETY_BACKUP="$BACKUP_DIR/before_restore_$(date +%Y%m%d_%H%M%S).sql"
echo ""
echo "📦 Creating safety backup first..."
pg_dump -U "$DB_USER" -h "$DB_HOST" "$DB_NAME" > "$SAFETY_BACKUP"
echo "✅ Safety backup: $SAFETY_BACKUP"

# Decompress if needed
if [[ "$BACKUP_FILE" == *.gz ]]; then
    echo ""
    echo "🗜️  Decompressing backup..."
    DECOMPRESSED="${BACKUP_FILE%.gz}"
    gunzip -c "$BACKUP_FILE" > "$DECOMPRESSED"
    BACKUP_FILE="$DECOMPRESSED"
fi

# Stop PM2
echo ""
echo "⏸️  Stopping PM2 processes..."
pm2 stop luckychit-api 2>/dev/null || true

# Drop and recreate
echo ""
echo "🗑️  Dropping existing database..."
dropdb -U "$DB_USER" -h "$DB_HOST" --if-exists "$DB_NAME"

echo "🆕 Creating fresh database..."
createdb -U "$DB_USER" -h "$DB_HOST" "$DB_NAME"

# Restore
echo ""
echo "📥 Restoring backup..."
psql -U "$DB_USER" -h "$DB_HOST" "$DB_NAME" < "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Database restored successfully!"
    
    # Clean up decompressed file
    if [[ "$BACKUP_FILENAME" == *.gz ]]; then
        rm -f "$BACKUP_FILE"
    fi
    
    # Restart PM2
    echo ""
    echo "▶️  Restarting PM2..."
    pm2 restart luckychit-api
    pm2 status
    
    echo ""
    echo "✅ Restore complete!"
    echo "📁 Safety backup: $SAFETY_BACKUP"
else
    echo ""
    echo "❌ Restore failed!"
    echo "📁 Safety backup available: $SAFETY_BACKUP"
    exit 1
fi

