name: Release

on:
  push:
    tags:
      - "v*"

# Only run on actual tag pushes, not branch pushes
# This prevents the workflow from triggering on commits to main that happen
# during the version bump process

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: false # Don't cancel releases

permissions:
  contents: write

jobs:
  create-release:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - name: Get token
        id: get_token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ secrets.ROVO_CD_APP_ID }}
          private-key: ${{ secrets.ROVO_CD_TOKEN }}
          owner: ${{ github.repository_owner }}
          repositories: ${{ github.event.repository.name }}

      - uses: actions/checkout@v5
        with:
          token: ${{ steps.get_token.outputs.token }}

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Build
        run: cargo build --release --all-features

      - name: Run tests
        run: cargo test --workspace --all-features --release

      - name: Extract version
        id: extract-version
        run: echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

      - name: Check crate version matches tag
        run: |
          # Check workspace version since all crates use workspace versioning
          CARGO_VERSION=$(grep -E "^version" Cargo.toml | head -1 | cut -d'"' -f2)
          if [ "$CARGO_VERSION" != "${{ steps.extract-version.outputs.version }}" ]; then
            echo "Error: Cargo.toml workspace version ($CARGO_VERSION) doesn't match tag version (${{ steps.extract-version.outputs.version }})"
            exit 1
          fi

      - name: Check if release already exists
        id: check_release
        run: |
          if gh release view "v${{ steps.extract-version.outputs.version }}" &>/dev/null; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Release v${{ steps.extract-version.outputs.version }} already exists, skipping creation"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
            echo "Release v${{ steps.extract-version.outputs.version }} does not exist, will create"
          fi
        env:
          GITHUB_TOKEN: ${{ steps.get_token.outputs.token }}

      - name: Create GitHub Release
        if: steps.check_release.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          token: ${{ steps.get_token.outputs.token }}
          generate_release_notes: true
          draft: false
          prerelease: ${{ contains(github.ref, '-rc') || contains(github.ref, '-beta') || contains(github.ref, '-alpha') }}
