name: Docs Remove Preview

on:
  workflow_run:
    workflows: [PR Closed]
    types:
      - completed

jobs:
  teardown:
    runs-on: ubuntu-latest
    if: github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'pull_request'
    steps:
      - name: Get PR number
        uses: actions/github-script@v6
        id: get_pr
        continue-on-error: true
        with:
          script: |
            let login = context.payload.workflow_run.head_repository.owner.login;
            let branch = context.payload.workflow_run.head_branch;
            let head = `${login}:${branch}`;
            let prs = await github.rest.pulls.list({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: "closed",
              head,
            });
            if (prs.data.length > 0) {
              core.setOutput("prnumber", prs.data[0].number);
            } else {
              core.setFailed("Could not find PR");
            }

      - name: Teardown preview
        if: steps.get_pr.outcome == 'success'
        continue-on-error: true
        uses: adrianjost/actions-surge.sh-teardown@v1.0.3
        with:
          regex: pr-${{ steps.get_pr.outputs.prnumber }}--ruma-docs.surge.sh
        env:
          SURGE_LOGIN: ${{ secrets.SURGE_LOGIN }}
          SURGE_TOKEN: ${{ secrets.SURGE_TOKEN }}

      - name: Remove PR preview URL
        if: steps.get_pr.outcome == 'success'
        uses: Beakyn/gha-comment-pull-request@v1.0.2
        env:
          GITHUB_TOKEN: ${{ github.token }}
        with:
          pull-request-number: ${{ steps.get_pr.outputs.prnumber }}
          description-message: |
            ----
            Preview Removed
