name: Auto Bump Dependencies

on:
  schedule:
    - cron: "0 4 * * *" # Run every day at 04:00 UTC
  workflow_dispatch:

jobs:
  auto-bump:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install npm-check-updates
        run: npm install -g npm-check-updates

      - name: Bump dependencies
        run: |
          # Upgrade while considering peer constraints to avoid TS/ESLint clashes
          ncu -u --peer
          # ncu -u --reject '/^typescript$/'

      - name: Install updated deps
        run: npm install

      - name: Run npm audit fix
        run: npm audit fix || true

      - name: Commit changes (bump + audit fix)
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add package.json package-lock.json
          git diff --cached --quiet || git commit -m "chore: bump dependencies and apply audit fix"
        continue-on-error: true

      - name: Run tests on updated deps
        id: test
        run: npm test
        continue-on-error: true

      - name: If tests pass, push to main
        if: steps.test.outcome == 'success'
        run: git push origin HEAD:main

      - name: If tests fail, create PR
        if: steps.test.outcome == 'failure'
        uses: peter-evans/create-pull-request@v5
        with:
          branch: bump-deps-failed
          title: "chore: bump dependencies and audit fix (tests failed)"
          body: |
            Dependencies were updated and `npm audit fix` was run, but tests failed.
            Please investigate and merge manually.
          commit-message: "chore: bump dependencies and audit fix (tests failed)"
