name: Deploy backend to prod VPS

# On a push to `release` that touches backend/**, SSH to prod and roll ONLY
# the backend service onto the image backend-build-push.yml published for this
# commit. Same shape as backend-deploy.yml (the `main`->beta path) against a
# completely separate secret set (PROD_SSH_HOST/USER/KEY/PORT) so a beta
# credential leak can't reach prod. Frontend deploys itself independently via
# frontend-deploy-prod.yml -- a backend change ships to prod without touching
# frontend and vice versa, exactly as in the split era.
#
# The tag MUST match backend-build-push.yml's last-backend-commit key (12
# hex) -- see backend-deploy.yml for why it's truncated here. deploy.sh
# retries the pull because the build for this push may still be in flight.

on:
  push:
    branches: [release]
    paths: ['backend/**']
  workflow_dispatch: {}

concurrency:
  group: prod-deploy-backend
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4
        # fetch-depth 0: the tag is keyed to the LAST COMMIT THAT TOUCHED THIS
        # DOMAIN, not the branch tip -- in a path-filtered monorepo the tip is
        # often an unrelated domain's commit, and a depth-1 clone can't see
        # past it to find the real key.
        with:
          fetch-depth: 0

      - name: Compute image tag (last backend-touching commit)
        id: tag
        run: |
          domain_sha="$(git log -1 --format=%H -- backend/)"
          echo "tag=sha-${domain_sha:0:12}" >> "$GITHUB_OUTPUT"

      - name: Deploy backend over SSH
        uses: https://github.com/appleboy/ssh-action@v1.2.0
        with:
          host: ${{ secrets.PROD_SSH_HOST }}
          username: ${{ secrets.PROD_SSH_USER }}
          key: ${{ secrets.PROD_SSH_KEY }}
          port: ${{ secrets.PROD_SSH_PORT }}
          # Forward the target service + the image tag to run. deploy.sh reads
          # BACKEND_IMAGE_TAG and rolls just `backend`.
          envs: SERVICE,BACKEND_IMAGE_TAG
          script: /opt/thermograph/infra/deploy/deploy.sh
        env:
          SERVICE: backend
          BACKEND_IMAGE_TAG: ${{ steps.tag.outputs.tag }}
