name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'

      - name: Run backend tests
        run: ./mvnw verify -B -q

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        uses: appleboy/ssh-action@v1
        with:
          host: plate-software.de
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            cd /opt/cannamanage
            git pull origin main
            docker compose -f docker-compose.prod.yml build
            docker compose -f docker-compose.prod.yml up -d
            
            # Wait for backend health
            sleep 15
            for i in 1 2 3 4 5; do
              if curl -sf http://127.0.0.1:8080/actuator/health > /dev/null 2>&1; then
                echo "✅ Deploy successful at $(date)"
                exit 0
              fi
              echo "Waiting... attempt $i/5"
              sleep 5
            done
            
            echo "❌ Deploy failed — backend unhealthy"
            docker compose -f docker-compose.prod.yml logs --tail=30 backend
            exit 1
