name: DevBuild Publish

on:
  push:
    branches:
      - main

permissions:
  contents: write

jobs:
  publish-devbuild:
    if: contains(github.event.head_commit.message, '[devbuild]')
    name: Publish DevBuild to NPM
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          persist-credentials: true

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/

      - name: Install dependencies
        run: npm ci

      - name: Patch version and rename to devbuilds
        id: bump_version
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "Current version: $CURRENT_VERSION"
          NEW_VERSION=$(npm version prerelease --preid=dev --no-git-tag-version)
          echo "Bumped version: $NEW_VERSION"
          echo "version_tag=$NEW_VERSION" >> $GITHUB_OUTPUT

          jq '.name = "@origami-minecraft/devbuilds"' package.json > tmp.json && mv tmp.json package.json
          git add package.json
          git commit -m "chore: bump to $NEW_VERSION"
          git push origin HEAD:main

      - name: Publish to NPM
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npm publish --access public

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.bump_version.outputs.version_tag }}
          name: "Dev Build ${{ steps.bump_version.outputs.version_tag }}"
          body: |
            This is an automated dev build released from main branch.
            Version: ${{ steps.bump_version.outputs.version_tag }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}