name: API NPM publish Continuous Deployment workflow

on:
  release:
    # This specifies that the build will be triggered when we publish a release
    types: [published]

jobs:
  build:
    # Run on latest version of ubuntu
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5
        with:
          # "ref" specifies the branch to check out.
          # "github.event.release.target_commitish" is a global variable and specifies the branch the release targeted
          ref: ${{ github.event.release.target_commitish }}
      # install Node.js
      - name: Use Node.js 18
        uses: actions/setup-node@v6
        with:
          node-version: 18
          # Specifies the registry, this field is required!
          registry-url: https://registry.npmjs.org/
      - name: Start MongoDB
        uses: supercharge/mongodb-github-action@1.12.0
        with:
          mongodb-version: 6.0
      - name: Install whole project dependencies
        # if: steps.yarn-cache.outputs.cache-hit != 'true' # I think we want to install every time,
        # but use the cache?
        run: yarn --frozen-lockfile
      # set up git since we will later push to the repo
      - run: git config --global user.name "GitHub CD bot"
      - run: git config --global user.email "github-cd-bot@nang.io"
      # upgrade npm version in package.json to the tag used in the release.
      - run: npm version ${{ github.event.release.tag_name }}
      # build the project
      - run: yarn build
      # run tests just in case
      - run: yarn test
      # publish to NPM -> there is one caveat, continue reading for the fix
      - run: npm publish
        env:
          # Use a token to publish to NPM. See below for how to set it up
          NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
      # create a PR with the version bump. We can't commit directly to the master branch because of branch protection.
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v7
        with:
          commit-message: "Bump package version to ${{ github.event.release.tag_name }}"
          committer: GitHub <noreply@github.com>
          author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>
          branch: package-json-${{ github.event.release.tag_name }}
          title: "[Publish] Bump package version to ${{ github.event.release.tag_name }}"
          assignees: joshgachnang
          reviewers: joshgachnang
      - name: Slack Notification
        uses: rtCamp/action-slack-notify@v2
        env:
          SLACK_CHANNEL: bots
          SLACK_COLOR: "#4BB543"
          # SLACK_MESSAGE: "Post Content :rocket:"
          SLACK_TITLE: Released ferns-ui@${{ github.event.release.target_commitish }}
          SLACK_USERNAME: Flourish
          SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
