# Changelog Generator
#
# Creates a PR to update CHANGELOG.md after a release is published.
# Uses git-cliff to generate changelog from conventional commits.

name: Changelog

on:
    release:
        types: [published]

permissions:
    contents: write
    pull-requests: write

jobs:
    changelog:
        name: Update Changelog
        runs-on: ubuntu-latest

        steps:
            - name: Checkout code
              uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  fetch-depth: 0

            - name: Generate changelog
              uses: orhun/git-cliff-action@c93ef52f3d0ddcdcc9bd5447d98d458a11cd4f72 # v4.7.1
              with:
                  config: cliff.toml
                  args: --verbose
              env:
                  OUTPUT: CHANGELOG.md
                  GITHUB_REPO: ${{ github.repository }}

            - name: Create Pull Request
              env:
                  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
              run: |
                  BRANCH="changelog/${{ github.event.release.tag_name }}"

                  git config --local user.email "github-actions[bot]@users.noreply.github.com"
                  git config --local user.name "github-actions[bot]"

                  # Check for changes
                  git add CHANGELOG.md
                  if git diff --cached --quiet CHANGELOG.md; then
                    echo "No changes to CHANGELOG.md"
                    exit 0
                  fi

                  git checkout -b "$BRANCH"
                  git commit -m "docs: update changelog for ${{ github.event.release.tag_name }}"
                  git push origin "$BRANCH"

                  gh pr create \
                    --title "docs: update changelog for ${{ github.event.release.tag_name }}" \
                    --body "This PR updates the CHANGELOG.md file for release ${{ github.event.release.tag_name }}." \
                    --label "documentation"
