name: npm-publish
on:
  push:
    branches:
      - main
    paths:
      - 'package.json'

jobs:
  npm-publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Fetch all history for all tags and branches

      - uses: actions/setup-node@v4
        with:
          node-version: 21

      - name: Get version from package.json
        id: package_version
        run: echo "VERSION=$(jq -r .version package.json)" >> $GITHUB_ENV

      - name: Check if the tag exists
        id: tag_check
        run: |
          if git rev-parse "v${{ env.VERSION }}" >/dev/null 2>&1; then
            echo "EXISTS=true" >> $GITHUB_ENV
          else
            echo "EXISTS=false" >> $GITHUB_ENV
          fi

      - name: Install Dependencies
        if: env.EXISTS == 'false'
        run: |
          npm install

      - name: 👷 Build again just in case
        if: env.EXISTS == 'false'
        run: |
          rm -rf ./dist
          npm run build

      - name: Commit the clean build for the tag
        if: env.EXISTS == 'false'
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email 'github-actions[bot]@users.noreply.github.com'
          commit_message=$'👷 MRjs Publish - Auto Dist For ${{ env.VERSION }} 👷\n\nChanges at '"${GITHUB_SHA}"
          git add .
          git commit -m "$commit_message"

      - name: Create Git tag
        if: env.EXISTS == 'false'
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email 'github-actions[bot]@users.noreply.github.com'
          git tag v${{ env.VERSION }}
          git push origin v${{ env.VERSION }}

      - name: Debug token availability
        if: env.EXISTS == 'false'
        run: |
          echo "Token length: ${#NPM_MJRS_PUBLISH}"

      - name: Publish to npm
        if: env.EXISTS == 'false'
        uses: JS-DevTools/npm-publish@v3
        with:
          token: ${{ secrets.NPM_MJRS_PUBLISH }}
