#!/bin/bash
set -e

echo "🔄 DocFast Rollback Script"
echo "=========================="

# Check if we're on the server
if [ ! -d "/root/docfast" ]; then
    echo "❌ This script should be run on the production server"
    exit 1
fi

cd /root/docfast

# List available rollback images
echo "📋 Available rollback images:"
ROLLBACK_IMAGES=$(docker images --format "table {{.Repository}}:{{.Tag}}\t{{.CreatedAt}}" | grep "docfast-docfast:rollback-" | head -10)

if [ -z "$ROLLBACK_IMAGES" ]; then
    echo "❌ No rollback images available"
    exit 1
fi

echo "$ROLLBACK_IMAGES"
echo ""

# Get the most recent rollback image
LATEST_ROLLBACK=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "docfast-docfast:rollback-" | head -n1)

if [ -z "$LATEST_ROLLBACK" ]; then
    echo "❌ No rollback image found"
    exit 1
fi

echo "🎯 Will rollback to: $LATEST_ROLLBACK"
echo ""

# Confirm rollback
read -p "⚠️ Are you sure you want to rollback? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Rollback cancelled"
    exit 1
fi

echo "🛑 Stopping current services..."
docker compose down --timeout 30

echo "🔄 Rolling back to $LATEST_ROLLBACK..."
docker tag $LATEST_ROLLBACK docfast-docfast:latest

echo "▶️ Starting services..."
docker compose up -d

echo "⏱️ Waiting for service to be ready..."
for i in {1..20}; do
    if curl -f -s http://127.0.0.1:3100/health > /dev/null; then
        echo "✅ Rollback successful! Service is healthy."
        break
    fi
    if [ $i -eq 20 ]; then
        echo "❌ Rollback failed - service is not responding"
        exit 1
    fi
    echo "⏳ Attempt $i/20 - waiting 3 seconds..."
    sleep 3
done

echo "📊 Service status:"
docker compose ps

echo "🎉 Rollback completed successfully!"