name: Create Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  pull-requests: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout main branch
        uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9
          run_install: false

      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: ~/.pnpm-store
          key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-

      - name: Install dependencies
        run: pnpm install --prefer-offline

      - name: Generate changelog
        run: pnpm changelog

      - name: Open changelog PR
        run: |
          BRANCH="chore/changelog-${{ github.ref_name }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git checkout -b "$BRANCH"
          git add CHANGELOG.md
          if git diff --staged --quiet; then
            echo "No changelog changes, skipping PR"
          else
            git commit -m "chore: update CHANGELOG.md for ${{ github.ref_name }}"
            git push origin "$BRANCH"
            gh pr create \
              --title "chore: update CHANGELOG.md for ${{ github.ref_name }}" \
              --body "Automated changelog update for release ${{ github.ref_name }}. Merge before publishing the draft release to trigger npm publish." \
              --base main \
              --head "$BRANCH"
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract release notes
        run: |
          VERSION="${{ github.ref_name }}"
          VERSION="${VERSION#v}"
          awk "/^## \[${VERSION}\]/{found=1; next} found && /^## \[/{exit} found{print}" CHANGELOG.md > /tmp/release-notes.md
          # Fall back to a placeholder if the section wasn't found
          if [ ! -s /tmp/release-notes.md ]; then
            echo "See [CHANGELOG.md](https://github.com/${{ github.repository }}/blob/main/CHANGELOG.md) for details." > /tmp/release-notes.md
          fi

      - name: Create draft GitHub Release
        run: |
          gh release create "${{ github.ref_name }}" \
            --title "${{ github.ref_name }}" \
            --notes-file /tmp/release-notes.md \
            --draft
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
