name: Publish

on:
  push:
    branches:
      - main

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest

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

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

      - name: Get package version
        id: get_version
        run: |
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT

      - name: Check version on npm
        id: check_version
        run: |
          NPM_VERSION=$(npm view @latitude-data/supergateway version 2>/dev/null || echo "0.0.0")
          if [ "${{ steps.get_version.outputs.version }}" != "$NPM_VERSION" ]; then
            echo "should_publish=true" >> $GITHUB_OUTPUT
          else
            echo "should_publish=false" >> $GITHUB_OUTPUT
          fi

      - name: Install dependencies
        if: steps.check_version.outputs.should_publish == 'true'
        run: npm install

      - name: Build package (with workspace dependencies)
        if: steps.check_version.outputs.should_publish == 'true'
        run: npm run build

      - name: Publish to npm
        if: steps.check_version.outputs.should_publish == 'true'
        run: npm publish --access public --no-git-checks

        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

