name: Tag Release

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]
    branches: [main]

concurrency:
  group: tag-release
  cancel-in-progress: false

permissions: {}

jobs:
  tag-release:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Generate app token
        id: app-token
        uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
        with:
          app-id: ${{ secrets.RELEASE_BOT_APP_ID }}
          private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}

      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          fetch-depth: 0
          ref: ${{ github.event.workflow_run.head_sha }}
          token: ${{ steps.app-token.outputs.token }}

      - name: Check for version bump
        id: check
        run: |
          version=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          if [ -z "$version" ]; then
            echo "::error::Failed to extract version from Cargo.toml"
            exit 1
          fi
          tag="v${version}"
          echo "version=${version}" >> "$GITHUB_OUTPUT"
          echo "tag_name=${tag}" >> "$GITHUB_OUTPUT"

          if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
            echo "Tag ${tag} already exists — no release needed"
            echo "release=false" >> "$GITHUB_OUTPUT"
          else
            echo "New version ${version} detected"
            echo "release=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Create and push tag
        if: steps.check.outputs.release == 'true'
        env:
          TAG_NAME: ${{ steps.check.outputs.tag_name }}
        run: |
          git tag "$TAG_NAME"
          git push origin "$TAG_NAME"
