name: 🔒 NPM Release Preview

on:
  push:
    branches:
      - master  # Only run this on master for now

jobs:
  release:
    name: NPM release
    runs-on: ubuntu-latest

    permissions:
      contents: write    # Needed to push tags
      packages: write    # Allow publishing to NPM

    steps:
      - name: 📦 Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # ensure full history for tags

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

      - name: 📥 Install dependencies
        run: |
            npm ci

      - name: 🧪 Run tests
        run: npm test

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5.0.7
        with:
            files: ./coverage/lcov/coverage.xml 
            token: ${{ secrets.CODECOV_TOKEN }}
            fail_ci_if_error: true

      - name: 🔍 Get current version
        id: version_info
        run: |
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          cat package.json
          echo "Current package version is: $CURRENT_VERSION"
          echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT

      - name: 🚨 Bump version
        id: version_step
        run: |
          npm version patch --no-git-tag-version
          NEW_VERSION=$(node -p "require('./package.json').version")
          cat package.json
          echo "Bumped to version: $NEW_VERSION"
          echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT

      - name: ✅ Commit and tag version
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add package.json package-lock.json
          git commit -m "chore: release ${{ steps.version_step.outputs.version }}"
          git tag -a ${{ steps.version_step.outputs.version }} -m "Release ${{ steps.version_step.outputs.version }}"
          git push origin master --follow-tags


      - name: 🧐 Preview npm package contents
        run: |
          echo "Previewing npm package contents for version ${{ steps.version_step.outputs.version }}..."
          npm pack --dry-run

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