name: Pipeline

on:
  push:
    branches: ['main']
  pull_request:
    branches: ['main']

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Setup Node.js 18
        uses: actions/setup-node@v3
        with:
          node-version: 18

      - name: Install project dependencies
        run: |
          npm install

      - name: Run tests
        run: |
          npm run test

      - name: Build project
        run: |
          npm run build

      - name: Upload build artifacts for publish job
        uses: actions/upload-artifact@v4
        with:
          name: build-artifacts
          path: |
            dist/
            package.json
            README.md

  publish:
    name: Publish
    runs-on: ubuntu-latest
    needs: build
    if: github.event_name == 'push'

    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

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

      - name: Download build artifacts from build job
        uses: actions/download-artifact@v4
        with:
          name: build-artifacts
      
      - name: Publish package to npm registry
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}