name: CI | Publish npm package
on:
  push:
    tags:
      - 'v*'
permissions:
  contents: write
  packages: write
  id-token: write
jobs:
  build-and-publish:
    # prevents this action from running on forks
    if: github.repository == 'underpostnet/pwa-microservices-template'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - name: Install required packages
        run: |
          sudo apt-get update -y
          sudo apt-get install -y sudo tar gzip bzip2 git curl

      - uses: actions/setup-node@v6
        with:
          node-version: '24.x'
          registry-url: 'https://registry.npmjs.org'

      - name: Install Dependencies
        run: npm ci

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

      - name: Dispatch release CD
        run: |
          curl -s -f -X POST \
            -H "Accept: application/vnd.github.v3+json" \
            -H "Authorization: token ${{ secrets.GIT_AUTH_TOKEN }}" \
            "https://api.github.com/repos/underpostnet/pwa-microservices-template/actions/workflows/release.cd.yml/dispatches" \
            -d '{"ref":"master"}'

  build-and-publish-ghpkg:
    # prevents this action from running on forks
    if: github.repository == 'underpostnet/pwa-microservices-template-ghpkg'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - uses: actions/setup-node@v6
        with:
          node-version: '24.x'
          registry-url: 'https://registry.npmjs.org'
          scope: '@underpostnet'

      - name: Install Dependencies
        run: npm ci

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

      - name: Setup node to publish to GitHub Packages
        uses: actions/setup-node@v6
        with:
          node-version: '24.x'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@underpostnet'

      - name: Publish to GitHub Packages
        run: |
          npm config set //npm.pkg.github.com/:_authToken=${{ secrets.GIT_AUTH_TOKEN }}
          echo "//npm.pkg.github.com/:_authToken=${{ secrets.GIT_AUTH_TOKEN }}" > ~/.npmrc
          echo "@underpostnet:registry=https://npm.pkg.github.com" >> ~/.npmrc
          npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GIT_AUTH_TOKEN }}
