name: Changelog & Tag Pipeline

on:
  push:
    branches:
      - master

jobs:
  changelog-and-tag:
    if: "!startsWith(github.event.head_commit.message, 'chore(release):')"
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.REPO_PAT }}

      - name: Configure Git Bot
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"

      - name: Extract Version from Cargo.toml
        id: extract
        run: |
          VERSION=$(grep -m 1 '^version = ' Cargo.toml | tr -d ' "' | sed 's/version=//')
          echo "VERSION=$VERSION" >> $GITHUB_ENV
          echo "Detected version: $VERSION"

      - name: Generate Changelog
        uses: TriPSs/conventional-changelog-action@v5
        with:
          github-token: ${{ secrets.REPO_PAT }}
          output-file: "CHANGELOG.md"
          skip-version-file: "true"
          skip-tag: "true"
          skip-bump: "true"
          skip-ci: "false"
          fallback-version: ${{ env.VERSION }}
          git-message: "chore(release): update changelog v${{ env.VERSION }}"
          git-user-name: "github-actions[bot]"
          git-user-email: "41898282+github-actions[bot]@users.noreply.github.com"

      - name: Check if Tag Already Exists
        id: check_tag
        run: |
          git pull origin master
          
          if git rev-parse "v${{ env.VERSION }}" >/dev/null 2>&1; then
            echo "Tag v${{ env.VERSION }} already exists. Skipping tag creation."
            echo "EXISTS=true" >> $GITHUB_ENV
          else
            echo "Tag v${{ env.VERSION }} is new."
            echo "EXISTS=false" >> $GITHUB_ENV
          fi

      - name: Create and Push Tag
        if: env.EXISTS == 'false'
        run: |
          TAG_NAME="v${{ env.VERSION }}"
          echo "Cutting new release tag: $TAG_NAME"
          
          # Changed to an ANNOTATED tag (-a) so the author is explicitly recorded
          git tag -a $TAG_NAME -m "Release $TAG_NAME"
          git push origin $TAG_NAME