name: Publish to NPM on tag

on:
  push:
    tags: ["v*"]
  workflow_dispatch:

jobs:
  # Gerbang tes WAJIB sebelum terbit. Tag push TIDAK memicu validate.yml
  # (itu cuma jalan di push/PR ke main), jadi tanpa job ini commit rusak
  # yang diberi tag bisa lolos terbit ke npm. Gate ini cegah itu.
  test:
    runs-on: windows-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - name: Fast smoke (parse + manifest + critical files)
        shell: pwsh
        run: |
          .\tests\smoke-fast.ps1
          if ($LASTEXITCODE -ne 0) { throw "fast-smoke failed (exit $LASTEXITCODE)" }
      - name: Cache PowerShell modules (Pester)
        id: cache-pester
        uses: actions/cache@v4
        with:
          path: ~\Documents\PowerShell\Modules
          key: psmodules-pester-v5-${{ runner.os }}
      - name: Install Pester (cache miss)
        if: steps.cache-pester.outputs.cache-hit != 'true'
        shell: pwsh
        run: Install-Module -Name Pester -MinimumVersion 5.0 -Force -SkipPublisherCheck -Scope CurrentUser
      - name: Run Pester tests
        shell: pwsh
        run: |
          cd $env:GITHUB_WORKSPACE
          .\tests\Run-Tests.ps1

  publish:
    runs-on: ubuntu-latest
    needs: test
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "20"
          registry-url: "https://registry.npmjs.org"

      - name: Verify version (tag mode) atau skip (manual dispatch)
        run: |
          PKG_VERSION=$(node -p "require('./package.json').version")
          echo "Package version: $PKG_VERSION"
          if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
            TAG_VERSION="${GITHUB_REF#refs/tags/v}"
            echo "Tag version: $TAG_VERSION"
            if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then
              echo "ERROR: Tag version ($TAG_VERSION) does not match package.json ($PKG_VERSION)"
              exit 1
            fi
            echo "OK: tag matches package.json"
          else
            echo "Not a tag trigger (GITHUB_REF=$GITHUB_REF). Skipping version match check."
            echo "Will publish package.json version: $PKG_VERSION"
          fi

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