name: Publish to npm

on:
  push:
    branches:
      - master
  workflow_dispatch:

concurrency:
  group: npm-publish
  cancel-in-progress: false

permissions:
  contents: read
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: npm-publish
    steps:
      - name: Checkout repository

        uses: actions/checkout@v5

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

      - name: Update npm
        run: npm install -g npm@latest
        
      - name: Install dependencies
        run: npm ci

      - name: Setup test dependencies
        run: |
          cd test/support/express3 && npm install
          cd ../express4 && npm install

      - name: Run tests
        run: npm test

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

      - name: Get published version
        id: published-version
        run: |
          PUBLISHED_VERSION=$(npm view prerender-node version 2>/dev/null || echo "0.0.0")
          echo "version=$PUBLISHED_VERSION" >> $GITHUB_OUTPUT

      - name: Compare versions
        id: version-check
        run: |
          CURRENT="${{ steps.current-version.outputs.version }}"
          PUBLISHED="${{ steps.published-version.outputs.version }}"
          
          echo "Current version: $CURRENT"
          echo "Published version: $PUBLISHED"
          
        
          SHOULD_PUBLISH=$(node -e "
            const current = '$CURRENT'.split('.').map(Number);
            const published = '$PUBLISHED'.split('.').map(Number);
            
            for (let i = 0; i < 3; i++) {
              if (current[i] > published[i]) {
                console.log('true');
                process.exit(0);
              }
              if (current[i] < published[i]) {
                console.log('false');
                process.exit(0);
              }
            }
            console.log('false');
          ")
          
          echo "should-publish=$SHOULD_PUBLISH" >> $GITHUB_OUTPUT
          echo "Should publish: $SHOULD_PUBLISH"

      - name: Publish to npm
        if: steps.version-check.outputs.should-publish == 'true'
        run: npm publish --access public --provenance

      - name: Output result
        run: |
          if [ "${{ steps.version-check.outputs.should-publish }}" == "true" ]; then
            echo "Published version ${{ steps.current-version.outputs.version }} to npm"
          else
            echo "⏭Version ${{ steps.current-version.outputs.version }} already exists-not publishing"
          fi
