#!/bin/bash
# CompareKit Restore Script
# Restores from a backup

BACKUP_DIR="../CompareKit-Backups"

echo "╔════════════════════════════════════════╗"
echo "║     CompareKit Restore System          ║"
echo "╚════════════════════════════════════════╝"
echo ""

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

# List available backups
echo "📋 Available backups:"
echo ""
ls -lht "$BACKUP_DIR"/*.tar.gz 2>/dev/null | nl
echo ""

# Count backups
BACKUP_COUNT=$(ls "$BACKUP_DIR"/*.tar.gz 2>/dev/null | wc -l)

if [ $BACKUP_COUNT -eq 0 ]; then
    echo "❌ No backups found!"
    exit 1
fi

# Ask user which backup to restore
echo "Enter the number of the backup to restore (1-${BACKUP_COUNT}):"
read -r BACKUP_NUM

# Get the selected backup file
BACKUP_FILE=$(ls -t "$BACKUP_DIR"/*.tar.gz | sed -n "${BACKUP_NUM}p")

if [ -z "$BACKUP_FILE" ]; then
    echo "❌ Invalid selection!"
    exit 1
fi

echo ""
echo "⚠️  WARNING: This will restore from:"
echo "   $BACKUP_FILE"
echo ""
echo "   Current files will be backed up first to:"
echo "   ${BACKUP_DIR}/pre-restore-backup-$(date +"%Y%m%d-%H%M%S").tar.gz"
echo ""
read -p "Continue? (yes/no): " CONFIRM

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

# Create backup of current state before restore
echo ""
echo "📦 Creating backup of current state..."
tar -czf "${BACKUP_DIR}/pre-restore-backup-$(date +"%Y%m%d-%H%M%S").tar.gz" \
  --exclude='node_modules' \
  --exclude='cache/*' \
  --exclude='generated/*' \
  --exclude='tmp/*' \
  .

# Restore the backup
echo "📥 Restoring backup..."
tar -xzf "$BACKUP_FILE" -C .

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Restore completed successfully!"
    echo ""
    echo "⚠️  Remember to:"
    echo "   1. Run: npm install (to restore node_modules)"
    echo "   2. Check your .env file"
    echo "   3. Restart your Node.js app if deployed"
else
    echo ""
    echo "❌ Restore failed!"
    exit 1
fi
