name: Release Alpha Package

on:
  issue_comment:
    types: [ created ]

jobs:
  triggerPrWorkflow:
    name: Trigger PR Workflow
    if: >
      github.event.issue.pull_request &&
      github.event.comment.body == '@toptal-bot run package:alpha-release'
    runs-on: ubuntu-latest
    permissions: write-all
    env:
      GITHUB_TOKEN: ${{ secrets.TOPTAL_DEVBOT_TOKEN }}
      NPM_TOKEN: ${{ secrets.NPM_TOKEN_PUBLISH }}
      STATUS_CHECK_NAME: Publish Alpha Package
      STATUS_TARGET_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
    steps:
      - name: Get the secrets from GSM
        id: secrets_manager
        uses: toptal/actions/gsm-secrets@main
        with:
          workload_identity_provider: projects/858873486241/locations/global/workloadIdentityPools/gha-pool/providers/github-com
          service_account: gha-davinci@toptal-ci.iam.gserviceaccount.com
          secrets_name: |-
            JENKINS_CLIENT_ID:toptal-ci/JENKINS_CLIENT_ID
            JENKINS_URL:toptal-ci/JENKINS_URL
            JENKINS_SA_CREDENTIALS:toptal-ci/JENKINS_SA_CREDENTIALS
            NPM_TOKEN_PUBLISH:toptal-ci/NPM_TOKEN_PUBLISH
            TOPTAL_DEVBOT_TOKEN:toptal-ci/TOPTAL_DEVBOT_TOKEN
            TOPTAL_TRIGGERBOT_TOKEN:toptal-ci/TOPTAL_TRIGGERBOT_TOKEN
            TOPTAL_TRIGGERBOT_USERNAME:toptal-ci/TOPTAL_TRIGGERBOT_USERNAME

      - name: Parse secrets
        id: parse_secrets
        uses: toptal/actions/expose-json-outputs@main
        with:
          json: ${{ steps.secrets_manager.outputs.secrets }}

      - name: Set ENV Variables
        run: |-
          echo "NPM_TOKEN=${{ steps.parse_secrets.outputs.NPM_TOKEN_PUBLISH }}" >> $GITHUB_ENV
          echo "GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }}" >> $GITHUB_ENV
          echo "GH_TOKEN=${{ secrets.GITHUB_TOKEN }}" >> $GITHUB_ENV
          echo "DEVBOT_TOKEN=${{ steps.parse_secrets.outputs.TOPTAL_DEVBOT_TOKEN }}" >> $GITHUB_ENV

      - name: Feedback on action started
        uses: actions/github-script@v7
        with:
          github-token: ${{ env.GITHUB_TOKEN }}
          script: |
            const { owner, repo } = context.issue;
            await github.reactions.createForIssueComment({ owner, repo, comment_id: context.payload.comment.id, content: '+1' });

      - id: branch
        uses: xt0rted/pull-request-comment-branch@v2.0.0

      - name: Specify branch
        id: get-branch
        run: |
          echo "branch=${{ steps.branch.outputs.head_ref }}" >> $GITHUB_OUTPUT
          echo "sha=${{ steps.branch.outputs.head_sha }}" >> $GITHUB_OUTPUT

      - name: Configure git user
        run: |
          git config --global user.email "bot@toptal.com"
          git config --global user.name "toptal-bot"

      - name: Checkout the latest code
        uses: actions/checkout@v3
        with:
          token: ${{ env.GITHUB_TOKEN }}
          ref: ${{ steps.get-branch.outputs.branch }}
          fetch-depth: 0 # otherwise, you will fail to push refs to dest repo

      - name: Set status check - pending
        uses: actions/github-script@v7
        with:
          github-token: ${{ env.GITHUB_TOKEN }}
          script: |
            const { owner, repo } = context.issue;
            await github.repos.createCommitStatus({
              repo,
              owner,
              state: 'pending',
              sha: "${{ steps.get-branch.outputs.sha }}",
              context: process.env.STATUS_CHECK_NAME,
              target_url: process.env.STATUS_TARGET_URL
            })

      - name: Trigger alpha package
        id: alpha-package
        uses: toptal/davinci-github-actions/build-publish-alpha-package@v20.0.0
        with:
          npm-token: ${{ env.NPM_TOKEN }}
          branch: ${{ steps.get-branch.outputs.branch }}

      - name: Check versions and post comment
        uses: actions/github-script@v7
        env:
          versions: ${{ steps.alpha-package.outputs.versions }}
        with:
          github-token: ${{ env.GITHUB_TOKEN }}
          script: |
            const { repo: { owner, repo }, issue } = context
            const { versions } = process.env

            let body
            if (versions) {
              body = "Your alpha package is ready 🎉<br/>" + versions.split(' ').reduce((acc, version) => {
                acc += `\`pnpm add ${version}\`<br/>`
                return acc
              }, '')
            } else {
              body = "No changed packages to publish ❌<br/>"
            }

            await github.issues.createComment({ issue_number: issue.number, owner, repo, body })
            if (!versions) {
              return core.setFailed('No changed packages to publish')
            }

      - name: Set status check - success / failure / error
        if: ${{ always() }}
        uses: actions/github-script@v7
        with:
          github-token: ${{ env.GITHUB_TOKEN }}
          script: |
            const { owner, repo } = context.issue;

            const status = "${{ job.status }}";
            const state = status === 'cancelled' ? 'error' : status;

            await github.repos.createCommitStatus({
              repo,
              owner,
              state,
              sha: "${{ steps.get-branch.outputs.sha }}",
              context: process.env.STATUS_CHECK_NAME,
              target_url: process.env.STATUS_TARGET_URL
            })

      - name: Create Alpha Jira deployment
        uses: toptal/actions/create-jira-deployment@main
        with:
          jenkins_url: ${{ steps.parse_secrets.outputs.JENKINS_URL }}
          jenkins_user: ${{ steps.parse_secrets.outputs.TOPTAL_TRIGGERBOT_USERNAME }}
          jenkins_token: ${{ steps.parse_secrets.outputs.TOPTAL_TRIGGERBOT_TOKEN }}
          jenkins_client_id: ${{ steps.parse_secrets.outputs.JENKINS_CLIENT_ID }}
          jenkins_sa_credentials: ${{ steps.parse_secrets.outputs.JENKINS_SA_CREDENTIALS }}
          token: ${{ env.DEVBOT_TOKEN }}
          environment: alpha-package
          environment-url: https://www.npmjs.com/package/@toptal/davinci?activeTab=versions
