name: Deploy to Production

on:
  push:
    branches: [ main, master ]
    tags: [ 'v*' ]
    paths-ignore:
      - '**.md'
      - '.gitignore'
      - '.cursor/**'

jobs:
  deploy-production:
    runs-on: ubuntu-latest
    if: github.event_name == 'push'
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      
      - name: Setup SSH
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
      
      - name: Deploy to Production Server
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.PROD_HOST }}
          username: ${{ secrets.PROD_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            set -e
            cd /var/www/platform/prod
            
            # Load environment configuration
            if [ -f .end.prod ]; then
              source .end.prod
            fi
            
            # Pull latest changes
            git pull origin main || git pull origin master || true
            
            # Backup database before deployment
            if [ "$BACKUP_BEFORE_DEPLOY" = "true" ]; then
              mkdir -p /var/www/platform/backups
              docker compose exec -T db pg_dump -U ${POSTGRES_USER} ${POSTGRES_DB} > /var/www/platform/backups/backup_$(date +%Y%m%d_%H%M%S).sql || true
            fi
            
            # Stop services gracefully
            docker compose down --timeout 30 || true
            
            # Build and start services
            docker compose build --no-cache
            docker compose up -d
            
            # Wait for services to be ready
            sleep 15
            
            # Run migrations
            docker compose exec -T web python manage.py migrate || true
            
            # Collect static files
            docker compose exec -T web python manage.py collectstatic --noinput || true
            
            # Clear cache
            docker compose exec -T web python manage.py clearcache || true
            
            # Restart services
            docker compose restart
            
            echo "✅ Production deployment completed successfully"
      
      - name: Health Check
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.PROD_HOST }}
          username: ${{ secrets.PROD_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            sleep 15
            docker compose ps
            curl -f http://localhost:8123/health/ || exit 1
            echo "✅ Health check passed"
      
      - name: Notify Deployment
        if: always()
        run: |
          echo "Deployment status: ${{ job.status }}"
          # Здесь можно добавить уведомления (Telegram, Slack, Email и т.д.)
