name: Release and Publish
on:
  push:
    tags:
      - 'v*.*.*'

env:
  CARGO_TERM_COLOR: always

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write       # Allows git push and creating releases
      pull-requests: read   # Allows git-cliff to read PR data
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Required for git-cliff to access full history

      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.toml') }}

      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.toml') }}

      - name: Install git-cliff
        run: cargo install git-cliff

      - name: Generate Changelog
        run: git-cliff -c cliff.toml -o CHANGELOG.md

      - name: Commit Changelog
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add CHANGELOG.md
          git commit -m "chore(release): update changelog for ${{ github.ref_name }}" || echo "No changes to commit"
          git push origin HEAD:main

      - name: Build (release)
        run: cargo build --release --verbose

      - name: Create GitHub Release
        uses: actions/create-release@v1
        with:
          tag_name: ${{ github.ref_name }}
          release_name: ${{ github.ref_name }}
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish to crates.io
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_API_KEY }}
