name: Deploy to Production
on:
  push:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: bmm-deploy
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: hetzner
    steps:
      - name: Pull from Gitea + rebuild containers
        run: |
          set -eo pipefail
          : "${HOME:=/root}"
          export HOME
          cd /opt/buildmymcpserver
          git fetch gitea main
          git reset --hard gitea/main
          docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
          docker system prune -f

      - name: Health check
        run: |
          set -e
          for i in $(seq 1 30); do
            code=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:4000/health 2>/dev/null || echo 000)
            if [ "$code" = "200" ]; then echo "API healthy after $i attempts"; exit 0; fi
            echo "wait $i/30 (got $code)"
            sleep 5
          done
          docker logs bmm-api --tail 60 || true
          exit 1
