#!/bin/bash
# Reply to a review comment and resolve its thread.
# Usage: pr-reply-resolve.sh <repo> <pr> <comment_id> <reply_body>
set -euo pipefail
REPO="$1"; PR="$2"; CID="$3"; BODY="$4"

# Post a threaded reply to the review comment.
gh api -X POST "repos/${REPO}/pulls/${PR}/comments/${CID}/replies" -f body="$BODY" >/dev/null
echo "replied to ${CID}"

# Find the review-thread node id that contains this comment, then resolve it.
OWNER="${REPO%%/*}"; NAME="${REPO##*/}"
THREAD_ID=$(gh api graphql -f query='
query($owner:String!,$name:String!,$pr:Int!){
  repository(owner:$owner,name:$name){
    pullRequest(number:$pr){
      reviewThreads(first:100){
        nodes{ id isResolved comments(first:50){ nodes{ databaseId } } }
      }
    }
  }
}' -F owner="$OWNER" -F name="$NAME" -F pr="$PR" \
  --jq ".data.repository.pullRequest.reviewThreads.nodes[] | select(.comments.nodes[].databaseId == ${CID}) | .id" | head -1)

if [ -z "$THREAD_ID" ]; then
  echo "WARN: no thread found for ${CID}"; exit 0
fi

gh api graphql -f query='
mutation($id:ID!){
  resolveReviewThread(input:{threadId:$id}){ thread{ isResolved } }
}' -F id="$THREAD_ID" --jq '.data.resolveReviewThread.thread.isResolved'
echo "resolved thread for ${CID}"
