name: Publish on tag
on:
  push:
    tags: [v*]

env:
  HTTPS_REMOTE: "https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"

jobs:
  publish:
    name: Publish Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
      - name: Install Dependencies
        run: npm i
      - name: Set up version
        run: |
          # Extract package name and version
          NPM_PACKAGE_NAME=$(node -p "require('./package.json').name")
          NPM_PACKAGE_VERSION=$(node -p "require('./package.json').version")
          echo "//registry.npmjs.org/:_authToken=${{ secrets.NODE_AUTH_TOKEN }}" > .npmrc
      - name: publish-dex
        run: |
          npm i
          npm run build
          # Publish to NPM registry
          npm publish --access public

  bump-version:
    needs: [publish]
    name: Bump SDK Version
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: "main"
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 18
      - name: Install tools
        run: npm i -g semver
      - name: Configure Git
        run: |
          git config --global user.name "galachain-release-bot"
          git config --global user.email "galachain-release-bot@users.noreply.github.com"
      - name: Set a new version
        run: |
          VERSION="$(semver "$(< package.json jq -r '.version')" -i)"
          echo "VERSION=$VERSION" >> $GITHUB_ENV
      - name: Create a new branch
        run: |
          BRANCH_NAME="bump-version-to-$VERSION"
          git checkout -b $BRANCH_NAME main
          echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
      - name: Bump version and commit changes
        run: |
          npm version $VERSION --no-git-tag-version
          npm i
          git commit -am "Bump version to $VERSION"
          git push --set-upstream origin bump-version-to-$VERSION
      - name: Create Pull Request
        env:
          GH_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
        run: gh pr create --title "Bump Version to $VERSION" --body "Bump Version to $VERSION" --label "bump-version-pr" --head "bump-version-to-$VERSION" --base main