name: Weekly Dependency Update

on:
  schedule:
    - cron: "0 0 * * 3" # Every Wednesday at 00:00 UTC (01:00 CET)
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  update-deps:
    name: Update Dependencies
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2

      - name: Run cargo update
        run: cargo update

      - name: Check for changes
        id: check
        run: |
          if git diff --quiet Cargo.lock; then
            echo "has_changes=false" >> "$GITHUB_OUTPUT"
          else
            echo "has_changes=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Generate update summary
        if: steps.check.outputs.has_changes == 'true'
        id: summary
        run: |
          {
            echo 'diff<<EOF'
            git diff Cargo.lock | head -500
            echo 'EOF'
          } >> "$GITHUB_OUTPUT"

      - name: Run tests
        if: steps.check.outputs.has_changes == 'true'
        run: cargo test --locked --all-features --all-targets

      - name: Run clippy
        if: steps.check.outputs.has_changes == 'true'
        run: cargo clippy -- -D warnings -A deprecated

      - name: Create Pull Request
        if: steps.check.outputs.has_changes == 'true'
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: "chore(deps): weekly cargo update"
          title: "chore(deps): weekly cargo update"
          body: |
            ## Automated Weekly Dependency Update

            This PR was automatically created by the **Weekly Dependency Update** workflow.

            `cargo update` was run to update all dependencies within their SemVer-compatible ranges.

            ### What was updated

            The following changes were made to `Cargo.lock`:

            ${{ steps.summary.outputs.diff }}

            ---

            > All tests and clippy checks have passed against the updated dependencies.
          branch: deps/weekly-cargo-update
          labels: dependencies
          delete-branch: true
