name: Auto Fix

on:
  pull_request:
    types: [opened, synchronize, reopened]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: write
  pull-requests: write

jobs:
  auto-fix:
    name: Auto Fix Issues
    runs-on: ubuntu-latest
    if: github.event.pull_request.head.repo.full_name == github.repository
    steps:
      - name: Generate App Token
        id: generate_token
        uses: tibdex/github-app-token@v2
        with:
          app_id: ${{ secrets.ROVO_CD_APP_ID }}
          private_key: ${{ secrets.ROVO_CD_TOKEN }}

      - uses: actions/checkout@v5
        with:
          token: ${{ steps.generate_token.outputs.token }}
          fetch-depth: 0
          ref: ${{ github.event.pull_request.head.ref }}

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - uses: Swatinem/rust-cache@v2

      - name: Run cargo fmt
        run: cargo fmt --all

      - name: Run cargo clippy fix
        run: |
          # Run clippy fix and capture the exit code
          # Exit code 101 means fixes were applied, which is expected
          cargo clippy --all-features --all-targets --fix --allow-staged --allow-dirty || EXIT_CODE=$?
          if [ "${EXIT_CODE:-0}" != "0" ] && [ "${EXIT_CODE:-0}" != "101" ]; then
            echo "Clippy failed with unexpected error code: ${EXIT_CODE}"
            exit 1
          fi

      - name: Check for changes
        id: verify-diff
        run: |
          git diff --quiet || echo "changed=true" >> $GITHUB_OUTPUT

      - name: Commit and push fixes
        if: steps.verify-diff.outputs.changed == 'true'
        run: |
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'
          git add -A
          git commit -m "chore(auto-fix): format code and fix clippy warnings"
          git push
