name: Publish NPM Package

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"

      - name: Extract version from tag
        id: version
        run: |
          echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

      - name: Wait for GitHub release
        run: |
          echo "Waiting for GitHub release v${{ steps.version.outputs.version }}..."
          i=1
          while [ $i -le 30 ]; do
            if curl -s -f "https://api.github.com/repos/safedep/pmg/releases/tags/v${{ steps.version.outputs.version }}" > /dev/null; then
              echo "Release found!"
              break
            fi
            if [ $i -eq 30 ]; then
              echo "Release not found after 10 minutes"
              exit 1
            fi
            echo "Waiting... ($i/30)"
            sleep 20
            i=$((i + 1))
          done

      - name: Prepare package
        run: |
          cd publish/npm
          npm version ${{ steps.version.outputs.version }} --no-git-tag-version

      - name: Publish to npm
        run: |
          cd publish/npm
          npm publish --provenance

  test-installation:
    needs: publish-npm
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        node-version: ["16", "18", "20"]

    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}

      - name: Extract version from tag
        id: version
        run: echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

      - name: Wait for npm package
        shell: bash
        run: |
          echo "Waiting for npm package..."
          i=1
          while [ $i -le 20 ]; do
            if npm view @safedep/pmg@${{ steps.version.outputs.version }} > /dev/null 2>&1; then
              echo "Package available!"
              break
            fi
            if [ $i -eq 20 ]; then
              echo "Package not available after 10 minutes"
              exit 1
            fi
            echo "Waiting... ($i/20)"
            sleep 30
            i=$((i + 1))
          done

      - name: Test installation
        run: |
          npm install -g @safedep/pmg@${{ steps.version.outputs.version }}
          pmg version
          pmg --help || true
