#!/bin/bash
# Get group members
source "$(dirname "$0")/config.sh"

TOKEN1=$(load_state "TOKEN1")
TOKEN2=$(load_state "TOKEN2")
GROUP_ID=$(load_state "GROUP_ID")

if [[ -z "$TOKEN1" || -z "$TOKEN2" || -z "$GROUP_ID" ]]; then
    echo "ERROR: Missing state. Run previous scripts first."
    echo "  TOKEN1=$TOKEN1"
    echo "  TOKEN2=$TOKEN2"
    echo "  GROUP_ID=$GROUP_ID"
    exit 1
fi

echo "=== Getting members of group $GROUP_ID as user1 (owner) ==="
RESP=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/get/group/members" \
    -d "token=$TOKEN1" \
    -d "group=$GROUP_ID")
BODY=$(echo "$RESP" | head -1)
CODE=$(echo "$RESP" | tail -1)
echo "Response: $BODY (HTTP $CODE)"

if [[ "$CODE" != "202" ]]; then
    echo "FAIL: Expected HTTP 202, got $CODE"
    exit 1
fi

echo ""
echo "=== Getting members of group $GROUP_ID as user2 (member) ==="
RESP=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/get/group/members" \
    -d "token=$TOKEN2" \
    -d "group=$GROUP_ID")
BODY=$(echo "$RESP" | head -1)
CODE=$(echo "$RESP" | tail -1)
echo "Response: $BODY (HTTP $CODE)"

if [[ "$CODE" != "202" ]]; then
    echo "FAIL: Expected HTTP 202, got $CODE"
    exit 1
fi

echo ""
echo "=== Getting members with invalid token ==="
RESP=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/get/group/members" \
    -d "token=invalid_token" \
    -d "group=$GROUP_ID")
BODY=$(echo "$RESP" | head -1)
CODE=$(echo "$RESP" | tail -1)
echo "Response: $BODY (HTTP $CODE)"

if [[ "$CODE" != "401" ]]; then
    echo "FAIL: Expected HTTP 401, got $CODE"
    exit 1
fi

echo ""
echo "=== Getting members with invalid group ID ==="
RESP=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/get/group/members" \
    -d "token=$TOKEN1" \
    -d "group=abc")
BODY=$(echo "$RESP" | head -1)
CODE=$(echo "$RESP" | tail -1)
echo "Response: $BODY (HTTP $CODE)"

if [[ "$CODE" != "400" ]]; then
    echo "FAIL: Expected HTTP 400, got $CODE"
    exit 1
fi

echo ""
echo "=== Getting members of non-existent group ==="
RESP=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/get/group/members" \
    -d "token=$TOKEN1" \
    -d "group=999999")
BODY=$(echo "$RESP" | head -1)
CODE=$(echo "$RESP" | tail -1)
echo "Response: $BODY (HTTP $CODE)"

if [[ "$CODE" != "401" ]]; then
    echo "FAIL: Expected HTTP 401, got $CODE"
    exit 1
fi

echo ""
echo "ALL PASSED"
