name: Deploy to Dev

on:
  push:
    branches: [ main, master, develop, dev ]

jobs:
  deploy-dev:
    runs-on: ubuntu-latest
    
    steps:
      - name: Deploy to Dev Server
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DEV_HOST }}
          username: ${{ secrets.DEV_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          use_insecure_cipher: true
          debug: true
          script_stop: true
          script: |
            set -e
            cd /var/www/platform/dev
            
            echo "📦 Pulling latest changes from repository..."
            git pull origin main || git pull origin master || git pull origin develop || git pull origin dev || true
            
            echo "🔄 Restarting Docker services..."
            docker compose restart
            
            echo "📊 Running migrations (if needed)..."
            docker compose exec -T web python manage.py migrate || true
            
            echo "📁 Collecting static files (if needed)..."
            docker compose exec -T web python manage.py collectstatic --noinput --clear || echo "⚠️  collectstatic failed, but continuing..."
            
            echo "✅ Dev deployment completed successfully"
            echo "ℹ️  You can continue working directly on the server"
      
      - name: Health Check
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DEV_HOST }}
          username: ${{ secrets.DEV_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          use_insecure_cipher: true
          debug: true
          script_stop: true
          script: |
            echo "⏳ Waiting for services to start..."
            sleep 15
            echo "📊 Checking Docker containers status..."
            docker compose ps
            echo "🏥 Checking health endpoint..."
            HEALTH_RESPONSE=$(curl -s http://localhost:8124/health/ || echo "")
            if [ -n "$HEALTH_RESPONSE" ]; then
              echo "✅ Health endpoint is responding"
              echo "$HEALTH_RESPONSE" | head -3
              # Check if web service is healthy (Celery may be unhealthy, but that's OK)
              if echo "$HEALTH_RESPONSE" | grep -q '"database".*"healthy"'; then
                echo "✅ Database is healthy"
              fi
            else
              echo "⚠️  Health endpoint not available, but deployment completed"
            fi
