on:
  workflow_run:
    workflows: [Danger (Generate)]
    types:
      - completed

name: Danger (Send)

jobs:
  send:
    name: Send
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - name: Checkout ScratchAddons/website-v2
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20.x
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/.github/workflows/danger-send.yml') }}
          restore-keys: ${{ runner.os }}-node-

      - name: Download artifact
        uses: actions/github-script@v7
        with:
          script: |
            let allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: context.payload.workflow_run.id,
            });
            let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "to-send"
            })[0];
            let download = await github.rest.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: 'zip',
            });
            let fs = require('fs');
            fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/to-send.zip`, Buffer.from(download.data));
      - name: Unzip artifact
        run: unzip to-send.zip

      # - name: Generate token 
      #   uses: tibdex/github-app-token@v1
      #   id: generate-token
      #   with:
      #     app_id: ${{ secrets.BOT_APP_ID }}
      #     private_key: ${{ secrets.BOT_PRIVATE_KEY }}
      - name: Execute script
        run: | 
          export PR_NUMBER=$(cat pr-number)
          export DANGER_TEST_PR=$PR_NUMBER
          rm -rf to-send.zip
          rm -rf pr-number
          npx danger ci
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
          DANGER_FAKE_CI: YEP
          DANGER_TEST_REPO: ${{ github.repository }}