# Rename this to whatever you want to call the workflow, or leave as is
name: Release

# Manual trigger
on:
  workflow_dispatch:
    inputs:
      version_bump:
        description: 'Version bump type'
        required: true
        default: 'patch'
        type: choice
        options:
          - patch
          - minor
          - major
  workflow_call:
    inputs:
      version_bump:
        required: true
        default: 'patch'
        type: string

# For automatic trigger, use this instead:
# on:
#   push:
#     branches: [main]
#   # Or trigger from another workflow:
#   # workflow_call:
#   #   secrets:
#   #     NPM_TOKEN:
#   #       required: true

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write # Required for creating releases and tags
      pull-requests: write # Required if you want to create PRs
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Important for correct version calculation

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc' # or use a .nvmrc file instead
          registry-url: 'https://registry.npmjs.org'

      # Configure Git user - if you want to use a different user, or leave as is to use the default git bot user
      - name: Configure Git
        run: |
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'

      # Install dependencies
      - name: Install dependencies
        run: npm install

      # Build the project
      - name: Build
        run: npm run build

      # xrelease will:
      # 1. Update version in package.json
      # 2. Generate/update CHANGELOG.md
      # 3. Commit these changes with message "chore(release): x.y.z"
      # 4. Create and push git tag vx.y.z
      # 5. Create GitHub release from the changelog
      - name: Create Release
        run: npx -y xrelease create --bump ${{ inputs.version_bump }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
