name: Release and Tag

on:
  workflow_run:
    workflows: ["Publish to npm"]
    types:
      - completed
  workflow_dispatch:
    inputs:
      version:
        description: 'The commit SHA or version to release'
        required: true

jobs:
  release:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Fetch all history for changesets to work correctly

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install dependencies
        run: npm ci

      - name: Version packages
        run: npm run version-packages
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Commit version changes
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"
          git add .
          git commit -m "chore: update versions and changelog [skip ci]" || echo "No changes to commit"
          git push

      - name: Create Git tag
        run: |
          VERSION=$(node -p "require('./package.json').version")
          git tag -a "v${VERSION}" -m "Release v${VERSION}"
          git push --tags
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}