name: Deploy PR Preview

on:
  workflow_run:
    workflows: [build]
    types:
      - completed

permissions:
  contents: read
  actions: write
  deployments: write

jobs:
  deploy-preview:
    runs-on: ubuntu-latest
    environment: workflows
    if: ${{github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'}}
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3

      - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: '24'
      - run: npm clean-install

      - name: Download all artifacts (dist folder and pr_metadata)
        uses: dawidd6/action-download-artifact@b6e2e70617bc3265edd6dab6c906732b2f1ae151 # v21
        with:
          github_token: ${{secrets.GITHUB_TOKEN}}
          run_id: ${{github.event.workflow_run.id}}
          allow_forks: true

      - name: Read pr_metadata
        id: pr_metadata
        run: cat pr_metadata/pr_metadata.ini >> $GITHUB_OUTPUT

      - 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.pr_metadata.outputs.pr}}

      - name: Run afterDeploy script
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const { afterDeploy } = await import('${{github.workspace}}/scripts/pr_preview.js');
            await afterDeploy({ core, github, context })(
              '${{steps.pr_metadata.outputs.pr}}',
              '${{steps.pr_metadata.outputs.ref}}',
            );
