name: Bump version in PR

on: [pull_request]

jobs:
  # If pull request was merged then we should check for a package version update
  check-version-update:
    runs-on: ubuntu-latest
    steps:
      # Checkout to target branch
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      # Get package new version name
      - name: Get package info
        id: packageNew
        uses: codex-team/action-nodejs-package-info@v1

      # Checkout to the base commit before merge
      - name: Checkout to the base commit before merge
        run: git checkout ${{ github.event.pull_request.base.sha }}

      # Get package old version name
      - name: Get package info
        id: packageOld
        uses: codex-team/action-nodejs-package-info@v1

      # Stop workflow and do not bump version if it was changed already
      - name: Stop workflow and do not bump version if it was changed already
        uses: andymckay/cancel-action@0.2
        if: steps.packageOld.outputs.version != steps.packageNew.outputs.version

  bump-version:
    needs: check-version-update
    runs-on: ubuntu-latest
    steps:
      # Checkout to target branch
      - uses: actions/checkout@v4

      # Setup node environment
      - uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc'
          registry-url: https://registry.npmjs.org/

      # Bump version to the next prerelease (patch) with rc suffix
      - name: Suggest the new version
        run: yarn version --patch --no-git-tag-version

      # Get package new version name
      - name: Get package info
        id: package
        uses: codex-team/action-nodejs-package-info@v1

      # Commit version upgrade
      - uses: EndBug/add-and-commit@v7
        with:
          author_name: github-actions
          author_email: 41898282+github-actions[bot]@users.noreply.github.com
          message: "Bump version up to ${{ steps.package.outputs.version }}"
