name: Assign User on Comment

on:
  workflow_dispatch:
  issue_comment:
    types: [created]

jobs:
  assign:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - name: Check for "/assigntome" in comment
        uses: actions/github-script@v6
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          script: |
            const issueComment = context.payload.comment.body;
            const assignRegex = /\/assigntome/i;
            if (assignRegex.test(issueComment)) {
              const assignee = context.payload.comment.user.login;
              const issueNumber = context.payload.issue.number;
              try {
                const { data: issue } = await github.rest.issues.get({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: issueNumber
                });
              const hasLabel = issue.labels.some(label => label.name === 'docathon-h1-2024');
              if (hasLabel) {
                if (issue.assignee !== null) {
                  await github.rest.issues.createComment({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    issue_number: issueNumber,
                    body: "The issue is already assigned. Please pick an opened and unnasigned issue with the [docathon-h1-2024 label](https://github.com/pytorch/pytorch/issues?q=is%3Aopen+is%3Aissue+label%3Adocathon-h1-2024)."
                  });
                } else {
                  await github.rest.issues.addAssignees({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    issue_number: issueNumber,
                    assignees: [assignee]
                  });
                }
              } else {
                const commmentMessage = "This issue does not have the correct label. Please pick an opened and unnasigned issue with the [docathon-h1-2024 label](https://github.com/pytorch/pytorch/issues?q=is%3Aopen+is%3Aissue+label%3Adocathon-h1-2024)."
                await github.rest.issues.createComment({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: issueNumber,
                  body: commmentMessage
                });
               }
              } catch (error) {
                console.error(error);
              }
            }
