#!/bin/bash
# Story: #1334 (Admin can manage Group memberships including nested groups)
# AC1:   Nested groups are supported: GroupMember.UserOrGroupId accepts
#        another Group's Id (not only a User Id)
#
# PASS:    POST GroupMember with UserOrGroupId=<another Group's Id> succeeds
# FAIL:    POST returns INSERT_FAILED / validation error / 4xx-5xx
# BLOCKED: parent Group create failed

# Related issues: pack#1105 (raw SQL leak — sanitizer landed via NX#568, behavior unchanged)
# Related upstream: NexusCRM#537 (polymorphic-FK sweep template)

. "$(dirname "$0")/../common/lib.sh"

TOK=$(get_admin_token) || {
  emit_verdict "#1334" "AC1" "BLOCKED" "admin token unavailable"
  exit 0
}

TS=$(date +%s)

G1_RESP=$(api_post "$TOK" "/sobjects/Group" "{
  \"Name\":\"qa_r6_g1_${TS}\",
  \"Label\":\"QA R6 G1 ${TS}\",
  \"Type\":\"Regular\"
}")
G1_ID=$(echo "$G1_RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)

G2_RESP=$(api_post "$TOK" "/sobjects/Group" "{
  \"Name\":\"qa_r6_g2_${TS}\",
  \"Label\":\"QA R6 G2 ${TS}\",
  \"Type\":\"Regular\"
}")
G2_ID=$(echo "$G2_RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)

if [ -z "$G1_ID" ] || [ -z "$G2_ID" ]; then
  [ -n "$G1_ID" ] && api_status "$TOK" DELETE "/sobjects/Group/$G1_ID" > /dev/null
  [ -n "$G2_ID" ] && api_status "$TOK" DELETE "/sobjects/Group/$G2_ID" > /dev/null
  emit_verdict "#1334" "AC1" "BLOCKED" "Group create failed (G1=$G1_ID G2=$G2_ID)"
  exit 0
fi

GM_RESP=$(api_post "$TOK" "/sobjects/GroupMember" "{
  \"GroupId\":\"$G1_ID\",
  \"UserOrGroupId\":\"$G2_ID\"
}")
GM_ID=$(echo "$GM_RESP" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('id','') if isinstance(d,dict) else '')" 2>/dev/null)

EV="gm_response=$(echo "$GM_RESP" | head -c 250)"

# Cleanup
[ -n "$GM_ID" ] && api_status "$TOK" DELETE "/sobjects/GroupMember/$GM_ID" > /dev/null
api_status "$TOK" DELETE "/sobjects/Group/$G2_ID" > /dev/null
api_status "$TOK" DELETE "/sobjects/Group/$G1_ID" > /dev/null

if [ -n "$GM_ID" ]; then
  emit_verdict "#1334" "AC1" "PASS" "gm_id=$GM_ID"
else
  emit_verdict "#1334" "AC1" "FAIL" "$EV"
fi
