name: Publish to npm

env:
  NODE_VERSION: '22.x'

on:
  push:
    branches:
      - main
    paths:
      - 'package.json'
      - 'generated/**'
      - 'src/**'
  workflow_dispatch:
    inputs:
      dry_run:
        description: 'Run in dry-run mode (no actual publish)'
        required: false
        type: boolean
        default: false

# Prevent concurrent publish operations
concurrency:
  group: npm-publish-${{ github.ref }}
  cancel-in-progress: false

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      should_publish: ${{ steps.check.outputs.should_publish }}
      package_version: ${{ steps.check.outputs.version }}
      npm_version: ${{ steps.check.outputs.npm_version }}
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
      
      - name: Get package version
        id: package
        run: |
          VERSION=$(node -p "require('./package.json').version")
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "Package version: ${VERSION}"
      
      - name: Check npm registry
        id: check
        run: |
          PACKAGE_VERSION="${{ steps.package.outputs.version }}"
          NPM_VERSION=$(npm view @elastic/ecs version 2>/dev/null || echo "0.0.0")

          echo "version=${PACKAGE_VERSION}" >> $GITHUB_OUTPUT
          echo "npm_version=${NPM_VERSION}" >> $GITHUB_OUTPUT

          if [ "${PACKAGE_VERSION}" = "${NPM_VERSION}" ]; then
            echo "❌ ERROR: Version ${PACKAGE_VERSION} already exists on npm!"
            echo "Current npm version: ${NPM_VERSION}"
            echo "Please bump the version in package.json before publishing."
            exit 1
          fi

          echo "should_publish=true" >> $GITHUB_OUTPUT
          echo "✅ Version ${PACKAGE_VERSION} is new (npm has ${NPM_VERSION})"

  publish:
    needs: check-version
    if: needs.check-version.outputs.should_publish == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
    
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
        with:
          node-version: ${{ env.NODE_VERSION }}
          registry-url: 'https://registry.npmjs.org'
          cache: 'yarn'
      
      - name: Install dependencies
        run: yarn install --frozen-lockfile
      
      - name: Build
        run: yarn build
      
      - name: Run tests
        run: |
          yarn test:unit
          yarn test:integration

#      npm trusted publishing requires npm CLI version 11.5.1+
      - name: Install npm 11.5.1 for trusted publishing
        run: npm install -g npm@11.5.1

      - name: Publish to npm (dry-run)
        if: inputs.dry_run == true
        run: npm publish --dry-run

      - name: Publish to npm
        if: inputs.dry_run != true
        run: npm publish --provenance --access public

      - name: Create git tag
        if: inputs.dry_run != true
        run: |
          VERSION="${{ needs.check-version.outputs.package_version }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a "v${VERSION}" -m "Release v${VERSION}"
          git push origin "v${VERSION}"
      
      - name: Create GitHub Release
        if: inputs.dry_run != true
        run: |
          VERSION="${{ needs.check-version.outputs.package_version }}"
          gh release create "v${VERSION}" \
            --title "v${VERSION}" \
            --notes "## @elastic/ecs v${VERSION}

          TypeScript definitions for Elastic Common Schema (ECS) version ${VERSION}.

          ### Installation
          \`\`\`bash
          npm install @elastic/ecs@${VERSION}
          # or
          yarn add @elastic/ecs@${VERSION}
          \`\`\`

          ### npm Package
          https://www.npmjs.com/package/@elastic/ecs/v/${VERSION}

          ### Changes
          This release includes updated TypeScript definitions generated from ECS schema version ${VERSION}." \
            --repo ${{ github.repository }}
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Summary
        if: inputs.dry_run != true
        run: |
          echo "## 🚀 Published to npm" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Package:** @elastic/ecs" >> $GITHUB_STEP_SUMMARY
          echo "**Version:** ${{ needs.check-version.outputs.package_version }}" >> $GITHUB_STEP_SUMMARY
          echo "**npm:** https://www.npmjs.com/package/@elastic/ecs/v/${{ needs.check-version.outputs.package_version }}" >> $GITHUB_STEP_SUMMARY
          echo "**Tag:** v${{ needs.check-version.outputs.package_version }}" >> $GITHUB_STEP_SUMMARY
