#!/bin/bash

echo "🚀 Starting deployment to new.sferav.ru..."

# Остановка предыдущей версии
echo "⏹️  Stopping previous version..."
docker-compose -f docker-compose.prod.yml down

# Очистка неиспользуемых образов
echo "🧹 Cleaning up unused images..."
docker image prune -f

# Сборка и запуск новой версии
echo "🔨 Building and starting new version..."
docker-compose -f docker-compose.prod.yml up -d --build

# Ожидание запуска
echo "⏳ Waiting for application to start..."
sleep 10

# Проверка здоровья
echo "🏥 Checking application health..."
for i in {1..30}; do
  if curl -f http://127.0.0.1:3017/api/health > /dev/null 2>&1; then
    echo "✅ Application is healthy!"
    break
  fi
  echo "⏳ Attempt $i/30 - waiting for health check..."
  sleep 2
done

# Проверка статуса контейнера
echo "📊 Container status:"
docker-compose -f docker-compose.prod.yml ps

echo "🎉 Deployment completed!"
echo "🌐 Application is available at: https://new.sferav.ru" 