name: Publish NPM Package

on:
  push:
    branches:
      - main
      - release/**
  
  # 允许手动触发发布
  workflow_dispatch:
    inputs:
      version_type:
        description: 'Version increment type'
        required: true
        default: 'patch'
        type: choice
        options:
          - patch
          - minor
          - major

jobs:
  publish:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # 获取完整的git历史，用于版本号管理

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          registry-url: 'https://registry.npmjs.org/'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run linting
        run: npm run lint
        
      - name: Run tests
        run: npm test
        
      - name: Build project
        run: npm run build
        
      - name: Configure Git user
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
        
      - name: Bump version (manual trigger)
        if: github.event_name == 'workflow_dispatch'
        run: |
          npm version ${{ github.event.inputs.version_type }} -m "chore: bump version to %s"
        
      - name: Bump version (auto trigger)
        if: github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/')
        run: |
          npm version patch -m "chore: bump version to %s"
        
      - name: Publish to npm
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        
      - name: Push version bump
        if: success() && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/')))
        run: git push
        
      - name: Notify on success
        if: success()
        run: |
          echo "✅ NPM package published successfully!"
          echo "📦 Package name: $(npm view . name)"
          echo "🔢 Version: $(npm view . version)"
        
      - name: Notify on failure
        if: failure()
        run: |
          echo "❌ NPM package publishing failed!"
          echo "📝 Check the logs above for details."
