name: Dependency Sync

on:
  repository_dispatch:
    types: [tls-updated]
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  RUSTFLAGS: "--cfg reqwest_unstable"

jobs:
  sync-tls:
    name: Update webclaw-tls dependencies
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          token: ${{ secrets.SYNC_PAT }}

      - uses: dtolnay/rust-toolchain@stable

      - name: Update webclaw-tls crates
        run: |
          cargo update -p webclaw-http -p rustls -p 'h2@0.4' -p 'hyper@1' -p 'hyper-util@0.1' -p 'reqwest@0.13' 2>&1

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

      - name: Commit and push
        if: steps.diff.outputs.changed == 'true'
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add Cargo.lock
          git commit -m "chore: update webclaw-tls dependencies"
          git push

      - name: Trigger server update
        if: steps.diff.outputs.changed == 'true'
        run: |
          gh api repos/0xMassi/webclaw-server/dispatches \
            -f event_type=core-updated \
            -f client_payload[sha]=${{ github.sha }}
        env:
          GH_TOKEN: ${{ secrets.SYNC_PAT }}
