name: Cleanup flue branches

on:
  schedule:
    - cron: "0 0 * * 1"
  workflow_dispatch:
    inputs:
      dry_run:
        description: "List stale branches without deleting them"
        type: boolean
        default: true

jobs:
  cleanup-flue-branches:
    if: github.repository == 'withastro/astro'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          persist-credentials: false

      - name: Setup node
        uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: 24.18.0

      - name: Find stale flue branches
        id: find-stale
        run: echo "branches=$(node --experimental-strip-types .github/scripts/stale-flue-branches.ts --token ${{ secrets.GITHUB_TOKEN }})" >> "$GITHUB_OUTPUT"

      - name: Delete stale flue branches
        if: steps.find-stale.outputs.branches != '[]'
        env:
          GH_TOKEN: ${{ secrets.FREDKBOT_GITHUB_TOKEN }}
          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
        run: |
          echo '${{ steps.find-stale.outputs.branches }}' | jq -r '.[]' | while read -r branch; do
            if [ "$DRY_RUN" = "true" ]; then
              echo "[dry-run] would delete $branch"
            else
              gh api --method DELETE "repos/${{ github.repository }}/git/refs/heads/$branch"
              echo "Deleted branch $branch"
            fi
          done
