name: Label Subissues
on:
  issues:
    types: [opened, edited]

jobs:
  apply-label:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - name: Check for Parent and Label
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          ISSUE_NODE_ID: ${{ github.event.issue.node_id }}
        run: |
          # Use GraphQL to check if this issue has a parent
          PARENT_ID=$(gh api graphql -f query='
            query($id: ID!) {
              node(id: $id) {
                ... on Issue {
                  parent {
                    id
                  }
                }
              }
            }' -f id=$ISSUE_NODE_ID --jq '.data.node.parent.id')

          # If PARENT_ID is not null, it is a subissue
          if [ "$PARENT_ID" != "null" ] && [ -n "$PARENT_ID" ]; then
            echo "Subissue detected. Applying label..."
            gh issue edit ${{ github.event.issue.number }} --add-label "subissue"
          else
            echo "This is a top-level issue."
          fi
