name: Claude Rebase

on:
  pull_request_target:
    types: [labeled]

jobs:
  rebase:
    environment: ai-bots
    if: github.event.label.name == 'cc:rebase'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Check PR author
        id: check-author
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            const allowedUsers = ['wwwillchen', 'wwwillchen-bot', 'azizmejri1', 'princeaden1'];
            if (!allowedUsers.includes(pr.user.login)) {
              console.log(`PR author ${pr.user.login} is not allowed to use this workflow`);
              core.setOutput('should_continue', 'false');
              return;
            }
            core.setOutput('should_continue', 'true');
            core.setOutput('pr_number', pr.number);

      - name: Checkout repository
        if: steps.check-author.outputs.should_continue == 'true'
        uses: actions/checkout@v4
        with:
          repository: ${{ github.event.pull_request.head.repo.full_name }}
          ref: ${{ github.event.pull_request.head.ref }}
          fetch-depth: 0

      - name: Remove cc:rebase label and add cc:rebasing
        if: steps.check-author.outputs.should_continue == 'true'
        run: |
          gh pr edit ${{ steps.check-author.outputs.pr_number }} --repo ${{ github.repository }} --remove-label "cc:rebase" --add-label "cc:rebasing"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Run PR Rebase
        if: steps.check-author.outputs.should_continue == 'true'
        uses: anthropics/claude-code-action@v1
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
          github_token: ${{ secrets.GITHUB_TOKEN }}
          prompt: |
            /dyad:pr-rebase ${{ steps.check-author.outputs.pr_number }}

      - name: Update labels on success
        if: steps.check-author.outputs.should_continue == 'true' && success()
        run: |
          gh pr edit ${{ steps.check-author.outputs.pr_number }} --repo ${{ github.repository }} --remove-label "cc:rebasing"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Update labels on failure
        if: steps.check-author.outputs.should_continue == 'true' && failure()
        run: |
          gh pr edit ${{ steps.check-author.outputs.pr_number }} --repo ${{ github.repository }} --remove-label "cc:rebasing" --add-label "cc:rebase-failed"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
