name: Update Changelog

on:
  workflow_dispatch: # Only manual trigger

# Add permissions for the GITHUB_TOKEN
permissions:
  contents: write

jobs:
  changelog:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Fetch full history for changelog generation
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install conventional-changelog-cli
        run: npm install -g conventional-changelog-cli conventional-changelog-angular

      - name: Generate changelog
        run: |
          # Create CHANGELOG.md if it doesn't exist
          if [ ! -f CHANGELOG.md ]; then
            echo "# Changelog" > CHANGELOG.md
            echo "" >> CHANGELOG.md
            echo "All notable changes to this project will be documented in this file." >> CHANGELOG.md
            echo "" >> CHANGELOG.md
          fi
          
          # Generate changelog using conventional commits
          conventional-changelog -p angular -i CHANGELOG.md -s

      - name: Check for changes
        id: verify-changed-files
        run: |
          if [ -n "$(git status --porcelain)" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Commit and push changes
        if: steps.verify-changed-files.outputs.changed == 'true'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add CHANGELOG.md
          git commit -m "chore: update changelog"
          git push origin main 