#!/bin/bash
# Replace the body of an existing comment on a Jira issue

set -e

# Arguments
ISSUE_KEY="$1"
COMMENT_ID="$2"
COMMENT="$3"

# Validation
if [ -z "$ISSUE_KEY" ] || [ -z "$COMMENT_ID" ] || [ -z "$COMMENT" ]; then
    echo "Error: Missing required arguments" >&2
    echo "Usage: $0 <issue-key> <comment-id> <new-body>" >&2
    echo "" >&2
    echo "Comment ids are listed in get-issue.sh output under fields.comment.comments[].id" >&2
    echo "The new body replaces the old one entirely; pass the full text." >&2
    exit 1
fi

# Check environment variables
if [ -z "$ATLASSIAN_SITE_NAME" ] || [ -z "$ATLASSIAN_USER_EMAIL" ] || [ -z "$ATLASSIAN_API_TOKEN" ]; then
    echo "Error: Jira environment variables not set" >&2
    exit 1
fi

# Build JSON payload
PAYLOAD=$(jq -n --arg comment "$COMMENT" '{body: $comment}')

# Update comment
curl -s -X PUT \
    -H "Content-Type: application/json" \
    -u "${ATLASSIAN_USER_EMAIL}:${ATLASSIAN_API_TOKEN}" \
    -d "$PAYLOAD" \
    "${ATLASSIAN_SITE_NAME}/rest/api/2/issue/${ISSUE_KEY}/comment/${COMMENT_ID}" \
    | jq '{id, created, updated}'
