name: Node.js Jobs

on:
  push:
    branches: [main]   # adjust as needed
    tags: [ '*' ]      # any tag

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

permissions:
  contents: write
  packages: write
  id-token: write

jobs:
  build_and_commit:
    name: Lint, Build & Auto-Commit if Needed
    runs-on: ubuntu-latest
    outputs:
      changed: ${{ steps.check_changes.outputs.changed }}
    steps:
      # 1. Checkout
      - uses: actions/checkout@v4

      # 2. Setup Node
      - uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
          cache: yarn

      # 3. Install dependencies
      - name: Install dependencies
        run: yarn install --frozen-lockfile

      # 4. Lint Check
      - name: Lint
        run: yarn lint

      # 5. Build
      - name: Build
        run: yarn build

      # 6. Check for git changes after build
      - name: Check for git changes
        id: check_changes
        run: |
          if [[ -n "$(git status --porcelain)" ]]; then
            echo "changed=true" >> "$GITHUB_OUTPUT"
          else
            echo "changed=false" >> "$GITHUB_OUTPUT"
          fi

      # 7. Auto-commit any changes produced by build
      - name: Auto-commit build artifacts
        if: steps.check_changes.outputs.changed == 'true' && !startsWith(github.ref, 'refs/tags/')
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "chore: Auto-commit build artifacts [skip ci]"

  publish:
    name: Publish to npm (on tag, if no build changes)
    needs: build_and_commit
    if: startsWith(github.ref, 'refs/tags/') && needs.build_and_commit.outputs.changed == 'false'
    runs-on: ubuntu-latest
    steps:
      # 1. Checkout
      - uses: actions/checkout@v4

      # 2. Setup Node
      - uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
          cache: yarn
          registry-url: 'https://registry.npmjs.org/'

      # 3. Install dependencies
      - name: Install dependencies
        run: yarn install --frozen-lockfile

      # 4. Publish
      - name: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npm publish --provenance --access public
