# Adapted from create-t3-app.
name: Write Beta Release comment

on:
  workflow_run:
    workflows: ["Release - Beta"]
    types:
      - completed

jobs:
  comment:
    if: |
      github.repository_owner == 'shadcn' &&
      ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest
    name: Write comment to the PR
    steps:
      - name: "Comment on PR"
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: context.payload.workflow_run.id,
            });

            for (const artifact of allArtifacts.data.artifacts) {
              // Extract the PR number and package version from the artifact name
              const match = /^npm-package-shadcn-ui@(.*?)-pr-(\d+)/.exec(artifact.name);
              
              if (match) {
                require("fs").appendFileSync(
                  process.env.GITHUB_ENV,
                  `\nBETA_PACKAGE_VERSION=${match[1]}` +
                  `\nWORKFLOW_RUN_PR=${match[2]}` +
                  `\nWORKFLOW_RUN_ID=${context.payload.workflow_run.id}`
                );
                break;
              }
            }

      - name: "Comment on PR with Link"
        uses: marocchino/sticky-pull-request-comment@v2
        with:
          number: ${{ env.WORKFLOW_RUN_PR }}
          message: |
            A new prerelease is available for testing:

            ```sh
            npx shadcn-ui@${{ env.BETA_PACKAGE_VERSION }}
            ```

      - name: "Remove the autorelease label once published"
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            github.rest.issues.removeLabel({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: '${{ env.WORKFLOW_RUN_PR }}',
              name: '🚀 autorelease',
            });
