# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
# https://docs.github.com/en/actions/language-and-framework-guides/publishing-nodejs-packages

# Description
name: Node.js Package

# Event to trigger the action
on:
  [push]
  # release:
  #  types: [created]

permissions:
  id-token: write # Required for OIDC
  contents: read

jobs:
  # Publish to NPM
  publish-npm:
    # Condition: previous build is successful
    # needs: Any previous jobs

    # Operation system
    runs-on: ubuntu-latest

    steps:
      # https://github.com/actions/checkout, This action checks-out your repository under $GITHUB_WORKSPACE
      # so your workflow can access it.
      - uses: actions/checkout@v5

      # Set up your GitHub Actions workflow with a specific version of node.js
      # Setup .npmrc file to publish to npm
      - uses: actions/setup-node@v6
        with:
          node-version: "24.11"
          registry-url: "https://registry.npmjs.org"

      # Named after Continuous Integration, installs dependencies directly from package-lock.json
      # ci vs install
      - run: npm install

      # Make sure pass the test without any exception
      - run: npm test

      # Build the package
      - run: npm run build

      # Check if the package is already published
      - name: Check publish status
        id: check
        uses: tehpsalmist/npm-publish-status-action@v1

      # Publish to npm
      # For scoped package, make it public for free service
      - name: Publish if necessary
        id: publish
        if: ${{ steps.check.outputs.exists == '0' }} # package version doesn't yet exist, ship it!
        run: npm publish

      - name: Report publish status
        if: ${{ steps.check.outputs.exists == '1' }}
        run: 'echo "package version already exists on npm registry"'
