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'
    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' && contains(github.event.comment.body, '/createissue') }}
        uses: actions/github-script@v8
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            const commentBody = context.payload.comment.body;
            const createIssueIndex = commentBody.indexOf('/createissue');
            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' && (contains(github.event.comment.body, '/close') || contains(github.event.comment.body, '/done')) }}
        uses: actions/github-script@v8
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            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' && contains(github.event.comment.body, '/movenextactiondateto') }}
        run: |
          DATE_STRING=$(echo "${{ github.event.comment.body }}" | grep -oP '(?<=/movenextactiondateto )\d{8}')
          OWNER=$(echo ${{ github.repository }} | cut -d '/' -f 1)
          REPO=$(echo ${{ github.repository }} | cut -d '/' -f 2)
          ITEM_ID=$(curl -X POST -H "Authorization: bearer ${{ secrets.GH_TOKEN }}" -H "Content-Type: application/json" --data '{ "query": "query { repository(owner: \"'$OWNER'\", name: \"'$REPO'\") { issue(number: '${{ github.event.issue.number }}') { projectItems(first: 10) { nodes { id } } } } }" }' https://api.github.com/graphql | jq -r '.data.repository.issue.projectItems.nodes[0].id')
          UPDATE_FIELD_DATA="{\"query\":\"mutation { updateProjectV2ItemFieldValue(input: {projectId: \\\"${{ env.project_v2_id }}\\\", fieldId: \\\"${{ env.field_id }}\\\", itemId: \\\"$ITEM_ID\\\", value: { date: \\\"$DATE_STRING\\\" }}) { clientMutationId }}\"}"
          curl --request POST \
            -f \
            --url https://api.github.com/graphql \
            --header "Authorization: Bearer ${{ env.gh_project_token }}" \
            --header "Content-Type: application/json" \
            --data "$UPDATE_FIELD_DATA"
      - name: Change Assignee
        if: ${{ github.event_name == 'issue_comment' && github.event.action == 'created' && contains(github.event.comment.body, '/changeassignee ') }}
        uses: actions/github-script@v8
        with:
          github-token: ${{secrets.GH_TOKEN}}
          script: |
            const commentBody = context.payload.comment.body;
            const assigneeIndex = commentBody.indexOf('/changeassignee ') + 16;
            const assigneeName = commentBody.slice(assigneeIndex).split(' ')[0].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@v2.2.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
        with:
          exclude-branches: 'release/**, dependabot/**, project-common/**, renovate/**'
          github-token: ${{ secrets.GH_TOKEN }}
          loose-matching: true
      - name: Get the output
        run: echo "How many linked issues? ${{ steps.check-linked-issues.outputs.linked_issues_count }}"
