name: Publish NPM package

on:
  push:
    branches: [master]

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

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

      - name: Set Git user
        run: |
          git config --local user.name "Yariv"
          git config --local user.email "yarivluts@gmail.com"

      - name: Bump version and create tag
        run: |
          npm version patch
          git push origin --tags
          git add .
          git push origin

      - name: Install dependencies
        run: npm ci

      - name: Build the package
        run: npm run build

      - name: Run critical tests before publish
        run: |
          npx jest test/scripts/esbuild.browser.bundle.test.ts --no-coverage
          npx jest test/scripts/admin.entry-point.test.ts --no-coverage

      - name: Verify bundle integrity
        run: |
          if grep -q "firebase-admin" dist/esm/index.js; then
            echo "ERROR: Main bundle contains firebase-admin - cannot publish"
            exit 1
          fi
          echo "✓ Bundle verification passed"

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