name: Publish to npm

on:
  release:
    types: [created]
  workflow_dispatch:
    inputs:
      version:
        description: 'Version type (patch/minor/major)'
        required: true
        default: 'patch'
        type: choice
        options:
          - patch
          - minor
          - major

jobs:
  publish:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
    
    - uses: actions/setup-node@v4
      with:
        node-version: '20.x'
        registry-url: 'https://registry.npmjs.org'
    
    - name: Configure Git
      run: |
        git config --global user.email "github-actions[bot]@users.noreply.github.com"
        git config --global user.name "GitHub Actions Bot"
    
    - name: Install dependencies
      run: npm ci
    
    - name: Build
      run: npm run build
    
    - name: Run tests
      run: npm test || true  # Don't block publish on test failures
    
    - name: Bump version (if manual trigger)
      if: github.event_name == 'workflow_dispatch'
      run: |
        npm version ${{ github.event.inputs.version }} --no-git-tag-version
        VERSION=$(node -p "require('./package.json').version")
        git add package.json package-lock.json
        git commit -m "🔖 Release v${VERSION} [skip ci]"
        git tag -a "v${VERSION}" -m "Release version ${VERSION}"
        git push origin HEAD --tags
    
    - name: Publish to npm
      run: npm publish --access public
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
    
    - name: Create GitHub Release (if manual trigger)
      if: github.event_name == 'workflow_dispatch'
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: v${{ steps.version.outputs.version }}
        release_name: Release v${{ steps.version.outputs.version }}
        body: |
          ## 🧬 Protein Hash v${{ steps.version.outputs.version }}
          
          Semantic code fingerprinting - see the soul of code!
          
          ### Install
          ```bash
          npm install @s0fractal/protein-hash@${{ steps.version.outputs.version }}
          ```
          
          ### Changes
          See [commits](https://github.com/s0fractal/protein-hash/commits/v${{ steps.version.outputs.version }})
        draft: false
        prerelease: false