name: Bot - PR Approval Command

on:
  issue_comment:
    types: [created]

jobs:
  approve:
    if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, '/approve') }}
    runs-on: ubuntu-latest
    steps:
      - name: Process Approval Command
        uses: actions/github-script@v9
        with:
          github-token: ${{ secrets.HOMEBREW_GITHUB_TOKEN }}
          script: |
            const commenter = context.payload.comment.user.login;
            const owner = context.repo.owner;
            const repo = context.repo.repo;
            const pr_number = context.issue.number;

            try {
              // 1. Verify membership in the floatpane organization
              await github.rest.orgs.checkMembershipForUser({
                org: 'floatpane',
                username: commenter,
              });

              // 2. Add an approving review
              await github.rest.pulls.createReview({
                owner,
                repo,
                pull_number: pr_number,
                event: 'APPROVE',
                body: `Approved on behalf of @${commenter} via \`/approve\` command.`
              });

              // Optionally add a reaction to the command comment to acknowledge it
              await github.rest.reactions.createForIssueComment({
                owner,
                repo,
                comment_id: context.payload.comment.id,
                content: 'rocket'
              });

            } catch (error) {
              if (error.status === 404) {
                // Not a member
                await github.rest.issues.createComment({
                  owner, repo, issue_number: pr_number,
                  body: `Sorry @${commenter}, only members of the \`floatpane\` organization can use the \`/approve\` command.`
                });
              } else {
                core.setFailed(`Error processing approval: ${error.message}`);
              }
            }
