name: Publish NPM Package to GitHub Packages and npm

on:
  workflow_dispatch:
  repository_dispatch:
    types: [trigger-publish]

jobs:
  publish:
    if: github.repository_owner == 'sy-records'

    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v6

      - name: Set up Node.js
        uses: actions/setup-node@v6
        with:
          node-version: "lts/*"

      - name: Generate nightly version
        run: |
          NIGHTLY_VERSION=5.0.0-nightly.$(git rev-parse --short HEAD)
          npm version $NIGHTLY_VERSION --no-git-tag-version

      - name: Authenticate with GitHub Packages
        run: |
          echo "//npm.pkg.github.com/:_authToken=${{ secrets.PUBLISH_GITHUB_TOKEN }}" > ~/.npmrc
          echo "registry=https://npm.pkg.github.com" >> ~/.npmrc

      - name: Test publish to GitHub Packages
        if: github.event_name == 'workflow_dispatch'
        run: |
          echo "Testing publish to GitHub Packages..."
          npm publish --tag nightly --dry-run --registry=https://npm.pkg.github.com

      - name: Publish to GitHub Packages
        if: github.event_name == 'repository_dispatch'
        run: npm publish --tag nightly --registry=https://npm.pkg.github.com

      - name: Authenticate with npm
        run: |
          echo "//registry.npmjs.org/:_authToken=${{ secrets.PUBLISH_NPM_TOKEN }}" >> ~/.npmrc

      - name: Test publish to npm registry
        if: github.event_name == 'workflow_dispatch'
        run: |
          echo "Testing publish to npm registry..."
          npm publish --tag nightly --dry-run --registry=https://registry.npmjs.org

      - name: Publish to npm registry
        if: github.event_name == 'repository_dispatch'
        run: npm publish --tag nightly --access public --registry=https://registry.npmjs.org
