name: Close stale PRs

on:
  schedule:
    - cron: "0 0 * * *" # daily at midnight UTC
  workflow_dispatch:

permissions:
  pull-requests: write

jobs:
  close-stale-prs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            const twoMonthsAgo = new Date();
            twoMonthsAgo.setMonth(twoMonthsAgo.getMonth() - 2);

            const prs = await github.paginate(github.rest.pulls.list, {
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'open',
              sort: 'created',
              direction: 'asc',
            });

            for (const pr of prs) {
              if (new Date(pr.created_at) >= twoMonthsAgo) {
                break;
              }
              try {
                await github.rest.issues.createComment({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: pr.number,
                  body: "Hi! We're closing this PR since it's been more than 2 months. Feel free to open a new PR if you'd like to continue. Thanks.",
                });

                await github.rest.pulls.update({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  pull_number: pr.number,
                  state: 'closed',
                });

                console.log(`Closed PR #${pr.number}: ${pr.title}`);
              } catch (error) {
                console.log(`Failed to close PR #${pr.number}: ${error.message}`);
              }
            }
