name: UMINO Project
on:
  issues:
    types:
      - opened
      - reopened
      - assigned
      - unassigned
      - labeled
  pull_request:
    types:
      - opened
      - reopened
      - review_requested
      - assigned
      - unassigned
      - labeled
      - opened
      - edited
      - reopened
      - synchronize
  issue_comment:
    types:
      - created
  pull_request_target:
    types:
      - opened
      - edited
      - reopened
      - synchronize

env:
  unread: Unread
  in_progress: In Progress
  gh_project_token: ${{ secrets.GH_TOKEN }}
  user: HiromiShikata
  project_id: 48
  project_v2_id: PVT_kwHOAGJHa84AFWnr
  field_id: PVTF_lAHOAGJHa84AFWnrzgIk_H0
  team_repo: '7sea.world, blog-tech, media-pinpoint-research, instagram-beauty-aesthetics-review, umino-corporait-operation, instagram-14LBaggageTraveler, hashigoya-project'

jobs:
  umino-job:
    if: (github.event_name != 'issue_comment' || github.event.comment.user.login != 'umino-bot') && github.event.action != 'labeled'
    runs-on: ubuntu-latest
    steps:
      - name: Move issue to ${{ env.unread }}
        uses: leonsteinhaeuser/project-beta-automations@v2.2.1
        with:
          gh_token: ${{ env.gh_project_token }}
          user: ${{ env.user }}
          project_id: ${{ env.project_id }}
          resource_node_id: ${{ github.event.pull_request.node_id || github.event.issue.node_id }}
          status_value: ${{ env.unread }}
        if: >-
          (github.event_name == 'issues' && github.event.issue.state == 'open') || 
          (github.event_name == 'pull_request' && github.event.pull_request.state == 'open') &&
          (github.event.action == 'opened' || github.event.action == 'reopened' || 
          github.event.action == 'assigned' || github.event.action == 'unassigned')
      - run: |
          OWNER=$(echo ${{ github.repository }} | cut -d '/' -f 1)
          REPO=$(echo ${{ github.repository }} | cut -d '/' -f 2)
          ENTITY_TYPE=$(echo ${{ github.event_name }} | grep -q "pull_request" && echo "pullRequest" || echo "issue")
          NUMBER=$(echo ${{ github.event_name }} | grep -q "pull_request" && echo ${{ github.event.pull_request.number }} || echo ${{ github.event.issue.number }})

          QUERY_DATA='{ "query": "query { repository(owner: \"'$OWNER'\", name: \"'$REPO'\") { '${ENTITY_TYPE}'(number: '$NUMBER') { projectItems(first: 10) { nodes { id } } } } }" }'
          RESPONSE=$(curl -X POST -H "Authorization: bearer ${{ secrets.GH_TOKEN }}" -H "Content-Type: application/json" --data "$QUERY_DATA" https://api.github.com/graphql)

          if echo $RESPONSE | grep -q "errors"; then
            echo "Error in GraphQL query"
            echo "GraphQL Response: $RESPONSE"
            exit 1
          fi

          if [ "$ENTITY_TYPE" = "pullRequest" ]; then
            ITEM_ID=$(echo $RESPONSE | jq -r '.data.repository.pullRequest.projectItems.nodes[0].id')
          else
            ITEM_ID=$(echo $RESPONSE | jq -r '.data.repository.issue.projectItems.nodes[0].id')
          fi

          if [ "$ITEM_ID" = "null" ] || [ -z "$ITEM_ID" ]; then
            echo "No valid item ID found, cannot proceed"
            exit 1
          fi

          CLEAR_FIELD_DATA="{\"query\":\"mutation { clearProjectV2ItemFieldValue(input: {projectId: \\\"${{ env.project_v2_id }}\\\", fieldId: \\\"${{ env.field_id }}\\\", itemId: \\\"$ITEM_ID\\\"}) { clientMutationId }}\"}"
          CLEAR_RESPONSE=$(curl --request POST \
            --url https://api.github.com/graphql \
            --header "Authorization: Bearer ${{ env.gh_project_token }}" \
            --header "Content-Type: application/json" \
            --data "$CLEAR_FIELD_DATA")

          if echo $CLEAR_RESPONSE | grep -q "errors"; then
            echo "Error in clearing field"
            echo "Clear Field Response: $CLEAR_RESPONSE"
            exit 1
          fi
        if: >-
          ((github.event_name == 'issues' && github.event.issue.state == 'open') ||
          (github.event_name == 'pull_request' && github.event.pull_request.state == 'open')) &&
          (github.event.action == 'opened' || github.event.action == 'reopened' ||
          github.event.action == 'assigned' || github.event.action == 'unassigned')

      - name: Create Issue
        if: ${{ github.event_name == 'issue_comment' && github.event.action == 'created' && github.event.comment.user.login == 'HiromiShikata' && contains(github.event.comment.body, '/createissue') }}
        uses: actions/github-script@v9
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            const commentBody = context.payload.comment.body;
            const commandMatch = /(^|\n)\s*\/createissue\b/m.exec(commentBody);
            if (!commandMatch) return;
            const createIssueIndex = commentBody.indexOf('/createissue', commandMatch.index);
            const issueTitle = commentBody.slice(createIssueIndex + 12).split('\n')[0].trim();
            const issueNumber = context.issue.number;
            const commentId = context.payload.comment.id;
            const commentLink = `https://github.com/${context.repo.owner}/${context.repo.repo}/issues/${issueNumber}#issuecomment-${commentId}`;
            const issueBody = `
            ${commentBody.slice(createIssueIndex + 12).trim()}
            Created from a comment: ${commentLink}
            `;
            const newIssue = await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: issueTitle,
              body: issueBody,
              assignees: ['HiromiShikata']
            });
      - name: Close Issue
        if: ${{ github.event_name == 'issue_comment' && github.event.action == 'created' && github.event.comment.user.login == 'HiromiShikata' && (contains(github.event.comment.body, '/close') || contains(github.event.comment.body, '/done')) }}
        uses: actions/github-script@v9
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            const body = context.payload.comment.body;
            if (!/(^|\n)\s*\/(close|done)\b/m.test(body)) return;
            await github.rest.issues.update({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              state: 'closed'
            });
      - name: Update Date Field
        if: ${{ github.event_name == 'issue_comment' && github.event.action == 'created' && github.event.comment.user.login == 'HiromiShikata' && contains(github.event.comment.body, '/movenextactiondateto') }}
        uses: actions/github-script@v9
        env:
          PROJECT_V2_ID: ${{ env.project_v2_id }}
          FIELD_ID: ${{ env.field_id }}
        with:
          github-token: ${{ secrets.GH_TOKEN }}
          script: |
            const commentBody = context.payload.comment.body;
            const commandMatch = /(^|\n)\s*\/movenextactiondateto\b/m.exec(commentBody);
            if (!commandMatch) return;
            const dateMatch = /\/movenextactiondateto\s+(\d{8})/.exec(commentBody.slice(commandMatch.index));
            if (!dateMatch) return;
            const dateString = dateMatch[1];
            const projectId = process.env.PROJECT_V2_ID;
            const fieldId = process.env.FIELD_ID;
            const itemIdResult = await github.graphql(
              `query($owner: String!, $repo: String!, $number: Int!) {
                repository(owner: $owner, name: $repo) {
                  issue(number: $number) {
                    projectItems(first: 10) { nodes { id } }
                  }
                }
              }`,
              { owner: context.repo.owner, repo: context.repo.repo, number: context.issue.number }
            );
            const itemId = itemIdResult.repository.issue.projectItems.nodes[0]?.id;
            if (!itemId) { core.setFailed('No project item found for this issue'); return; }
            await github.graphql(
              `mutation($projectId: ID!, $fieldId: ID!, $itemId: ID!, $date: Date!) {
                updateProjectV2ItemFieldValue(input: {
                  projectId: $projectId, fieldId: $fieldId, itemId: $itemId,
                  value: { date: $date }
                }) { clientMutationId }
              }`,
              { projectId, fieldId, itemId, date: dateString }
            );
      - name: Change Assignee
        if: ${{ github.event_name == 'issue_comment' && github.event.action == 'created' && github.event.comment.user.login == 'HiromiShikata' && contains(github.event.comment.body, '/changeassignee ') }}
        uses: actions/github-script@v9
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            const commentBody = context.payload.comment.body;
            const commandMatch = /(^|\n)\s*\/changeassignee\s+(\S+)/m.exec(commentBody);
            if (!commandMatch) return;
            const assigneeName = commandMatch[2].trim();
            await github.rest.issues.update({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              assignees: [assigneeName]
            });
      - name: Auto assign issue for non-team repositories
        if: >-
          github.event_name == 'issues' && 
          github.event.action == 'opened' && 
          !contains(env.team_repo, github.event.repository.name)
        uses: pozil/auto-assign-issue@v3.0.0
        with:
          assignees: HiromiShikata
          repo-token: ${{ secrets.GH_TOKEN }}

  check_pull_requests_to_link_issues:
    runs-on: ubuntu-latest
    name: Check linked issues in pull requests
    if: >-
      (github.event_name == 'pull_request')
    steps:
      - uses: nearform-actions/github-action-check-linked-issues@v1
        id: check-linked-issues
        if: github.event.pull_request.user.login != 'dependabot[bot]'
        with:
          exclude-branches: 'release/**, dependabot/**, project-common/**, renovate/**'
          github-token: ${{ secrets.GH_TOKEN }}
          loose-matching: true
          skip-linked-issues-check-label: ''
      - name: Get the output
        run: echo "How many linked issues? ${{ steps.check-linked-issues.outputs.linked_issues_count }}"
