name: Test and Release

on:
  push:
    branches: [ "**" ]
  pull_request:
    branches: [ "**" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install stable toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      - name: Rust Cache
        uses: swatinem/rust-cache@v2
      - name: Check formatting
        run: cargo fmt --all -- --check
      - name: Lint with clippy
        run: cargo clippy -- -D warnings
      - name: Build
        run: cargo build --verbose
      - name: Run tests
        run: cargo test --verbose

  release:
    name: Release
    runs-on: ubuntu-latest
    needs: test
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    permissions:
      contents: write
      pull-requests: read
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Install release-plz (Manual)
        run: |
          curl -L -o release-plz.tar.gz https://github.com/MarcoIeni/release-plz/releases/latest/download/release-plz-x86_64-unknown-linux-gnu.tar.gz
          tar xf release-plz.tar.gz
          sudo mv release-plz /usr/local/bin/
          rm release-plz.tar.gz

      - name: Run CI Checks
        run: |
          cargo test
          cargo clippy -- -D warnings

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

      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
        run: |
          release-plz update --verbose
          if [[ -n $(git status -s) ]]; then
            echo "Changes detected. Preparing release..."
            git add .
            git commit -m "chore: release"
            git push origin main
          fi
          release-plz release --verbose --git-token "${{ secrets.GITHUB_TOKEN }}" --backend github
