name: integration-pr

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  check-token:
    runs-on: ubuntu-latest
    environment: "test-trigger-is"

    outputs:
      has_token: ${{ steps.set-token-status.outputs.has_token }}

    steps:
      - name: Check if DECO_WORKFLOW_TRIGGER_APP_ID is set
        id: set-token-status
        run: |
          if [ -z "${{ secrets.DECO_WORKFLOW_TRIGGER_APP_ID }}" ]; then
            echo "DECO_WORKFLOW_TRIGGER_APP_ID is empty. User has no access to secrets."
            echo "::set-output name=has_token::false"
          else
            echo "DECO_WORKFLOW_TRIGGER_APP_ID is set. User has access to secrets."
            echo "::set-output name=has_token::true"
          fi

  # Trigger for pull requests.
  #
  # This workflow triggers the integration test workflow in a different repository.
  # It requires secrets from the "test-trigger-is" environment, which are only available to authorized users.
  # It depends on the "check-token" workflow to confirm access to this environment to avoid failures.
  trigger:
    runs-on: ubuntu-latest
    environment: "test-trigger-is"

    if: needs.check-token.outputs.has_token == 'true'
    needs: check-token

    steps:
      - name: Generate GitHub App Token
        id: generate-token
        uses: actions/create-github-app-token@v1
        with:
          app-id: ${{ secrets.DECO_WORKFLOW_TRIGGER_APP_ID }}
          private-key: ${{ secrets.DECO_WORKFLOW_TRIGGER_PRIVATE_KEY }}
          owner: ${{ secrets.ORG_NAME }}
          repositories: ${{secrets.REPO_NAME}}

      - name: Trigger Workflow in Another Repo
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
        run: |
          gh workflow run cli-isolated-pr.yml -R ${{ secrets.ORG_NAME }}/${{secrets.REPO_NAME}} \
          --ref main \
          -f pull_request_number=${{ github.event.pull_request.number }} \
          -f commit_sha=${{ github.event.pull_request.head.sha }}