name: Manual LGTM

on:
  issue_comment:
    types:
      - created

permissions:
  contents: read
  issues: read
  pull-requests: read
  statuses: write

jobs:
  lgtm:
    name: Apply Manual LGTM
    if: github.event.issue.pull_request != null && startsWith(github.event.comment.body, '/lgtm')
    runs-on: ubuntu-latest
    steps:
      - name: Validate commenter permission and set status
        uses: actions/github-script@v7
        with:
          script: |
            const owner = context.repo.owner;
            const repo = context.repo.repo;
            const issueNumber = context.issue.number;
            const commenter = context.payload.comment.user.login;

            const permission = await github.rest.repos.getCollaboratorPermissionLevel({
              owner,
              repo,
              username: commenter,
            });

            const allowed = new Set(['admin', 'maintain', 'write']);
            if (!allowed.has(permission.data.permission)) {
              core.notice(`Skipping /lgtm from ${commenter}: permission=${permission.data.permission}`);
              return;
            }

            const pull = await github.rest.pulls.get({
              owner,
              repo,
              pull_number: issueNumber,
            });

            await github.rest.repos.createCommitStatus({
              owner,
              repo,
              sha: pull.data.head.sha,
              state: 'success',
              context: 'Manual LGTM',
              description: `Approved by /lgtm from ${commenter}`,
              target_url: context.payload.comment.html_url,
            });
