name: Deploy Preview

on:
  workflow_run:
    workflows: ["Build Preview"]
    types:
      - completed
permissions:
  pull-requests: write
  actions: write
jobs:
  deploy-preview:
    environment: pr-previews
    runs-on: ubuntu-latest
    if: ${{github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'}}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
        with:
          node-version-file: '.nvmrc'

      - name: Get pull request number artifact
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          name: pr
          path: ./tmp-pr-artifact
          run-id: ${{github.event.workflow_run.id}}

      - name: Get pull request number
        id: pull-request-number
        run: echo "result=$(cat ./tmp-pr-artifact/pr_number)" >> "$GITHUB_OUTPUT"

      - uses: dawidd6/action-download-artifact@d63b86af1b34672e53c440b1b83979861906bad7 # v24
        with:
          github_token: ${{secrets.GITHUB_TOKEN}}
          workflow: build-preview.yml
          pr: ${{steps.pull-request-number.outputs.result}}
          name: preview
          allow_forks: true

      - name: Deploy to Netlify
        env:
          NETLIFY_AUTH_TOKEN: ${{secrets.NETLIFY_AUTH_TOKEN}}
          NETLIFY_SITE_ID: ${{secrets.NETLIFY_SITE_ID}}
        run: npx netlify-cli deploy --no-build --dir=. --alias=pr-${{steps.pull-request-number.outputs.result}}

      - name: Add comment to pull request
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const pullRequestNumber = parseInt(${{steps.pull-request-number.outputs.result}}, 10);
            const start = ':bento:';
            const author = 'github-actions[bot]';
            const previewDataUrl = `https://pr-${pullRequestNumber}--ideditor-presets-preview.netlify.app/dist/`;
            const idPreviewUrl = `https://pr-${pullRequestNumber}--ideditor-presets-preview.netlify.app/id/dist/#locale=en&map=18.00/48.841708/2.587656`;
            const browserCompareUrl =
              `https://osmberlin.github.io/tagging-schema-browser/comparison?dataUrl=${encodeURIComponent(previewDataUrl)}`;
            const comments = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: pullRequestNumber
            });
            const commentExists = comments.data.some(
              comment => comment.user.login === author && comment.body.startsWith(start)
            );
            if (!commentExists) {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pullRequestNumber,
                body: `${start} **[Your pull request preview is ready](${idPreviewUrl})**\n\nPlease use this preview to check your changes. Ideally use [the **test documentation** template](https://github.com/openstreetmap/id-tagging-schema/blob/main/.github/PULL_REQUEST_TEMPLATE.md?plain=1#L38-L69) and document your test results by commenting on the PR. This will speed up the review process for everyone.\n\n**Use the [Compare View on the Tagging Schema Browser (alpha)](${browserCompareUrl})** to see the changes of your PR against the \`main\` branch.\n\nFYI, once this PR is merged, you can use [the iD Editor Preview](http://preview.ideditor.com/) to test your changes in interaction with all other changes.`
              });
            } else {
              console.log(`Preview URL comment already added to PR #${pullRequestNumber}`);
            }

      - name: Clean up artifact
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          result-encoding: string
          script: |
            const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{github.event.workflow_run.id}}
            });
            const artifact = artifacts.data.artifacts.filter(
              artifact => artifact.name === 'preview'
            )[0];
            if (!artifact) {
              throw new Error('No "preview" artifact found');
            }
            await github.rest.actions.deleteArtifact({
              owner: context.repo.owner,
              repo: context.repo.repo,
              artifact_id: artifact.id
            });
