name: Auto Close Issues if Not Starred

on:
  issues:
    types: [opened]

jobs:
  close_issue:
    runs-on: ubuntu-latest
    steps:
    - name: Check if user has starred the repo
      id: check_star
      run: |
        ISSUE_USER=$(jq -r '.issue.user.login' < $GITHUB_EVENT_PATH)
        echo "Issue created by user: $ISSUE_USER"
        PAGE=1
        STARRED=""
        
        while [[ -z "$STARRED" ]]; do
          STARRED_RESPONSE=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
              "https://api.github.com/repos/${{ github.repository }}/stargazers?per_page=100&page=$PAGE")
          echo "STARRED_RESPONSE=$STARRED_RESPONSE"  # 输出 API 返回的数据以检查结构

          if [[ -z "$STARRED_RESPONSE" || "$STARRED_RESPONSE" == "[]" ]]; then
            break
          fi

          STARRED=$(echo "$STARRED_RESPONSE" | jq -r '.[] | select(.login == "'$ISSUE_USER'") | .login')
          PAGE=$((PAGE + 1))
        done

        if [[ -z "$STARRED" ]]; then
          echo "User has not starred the repo."
        else
          echo "User has starred the repo."
        fi

        echo "starred=$STARRED" >> $GITHUB_ENV




    - name: Close issue if not starred
      if: env.starred == '0'
      run: |
        ISSUE_NUMBER=$(jq -r '.issue.number' < $GITHUB_EVENT_PATH)
        echo "Closing issue #$ISSUE_NUMBER"
        curl -s -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
        -H "Accept: application/vnd.github.v3+json" \
        https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER/comments \
        -d '{"body":"Please star the project before submitting an issue."}'

        curl -s -X PATCH -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
        -H "Accept: application/vnd.github.v3+json" \
        https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER \
        -d '{"state":"closed"}'
