name: Deploy PR to Netlify
run-name: "Deploy PR to Netlify (${{ github.event.workflow_run.head_branch }})"

on:
  workflow_run:
      workflows: ["Build pull request"]
      types: [completed]

jobs:
  deploy-pull-request:
    name: Deploy pull request
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - name: Download pr number
        uses: dawidd6/action-download-artifact@b6e2e70617bc3265edd6dab6c906732b2f1ae151 # v21
        with:
          workflow: ${{ github.event.workflow.id }}
          run_id: ${{ github.event.workflow_run.id }}
          name: pr
      - name: Validate and output pr number
        id: pr
        run: |
          PR_ID=$(<pr.txt)
          if ! [[ "${PR_ID}" =~ ^[0-9]+$ ]]; then
            echo "::error::pr.txt contains non-numeric content: ${PR_ID}"
            exit 1
          fi
          echo "id=${PR_ID}" >> "${GITHUB_OUTPUT}"
      - name: Download artifact
        uses: dawidd6/action-download-artifact@b6e2e70617bc3265edd6dab6c906732b2f1ae151 # v21
        with:
          workflow: ${{ github.event.workflow.id }}
          run_id: ${{ github.event.workflow_run.id }}
          name: preview
          path: dist
      - name: Deploy to Netlify
        id: netlify
        uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654 # v3.0.0
        with:
          publish-dir: dist
          deploy-message: "Deploy PR ${{ steps.pr.outputs.id }}"
          alias: ${{ steps.pr.outputs.id }}
          # These don't work because we're in workflow_run
          enable-pull-request-comment: false
          enable-commit-comment: false
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN_PR }}
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_PR_CINNY }}
        timeout-minutes: 1
      - name: Comment preview on PR
        uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b #v3.0.1
        env:
          github-token: ${{ secrets.GITHUB_TOKEN }}
        with:
          pr-number: ${{ steps.pr.outputs.id }}
          comment-tag: ${{ steps.pr.outputs.id }}
          message: |
              Preview: ${{ steps.netlify.outputs.deploy-url }}
              ⚠️ Exercise caution. Use test accounts. ⚠️
