#!/bin/bash
# Send message from user_two to the group via HTTP, verify user_one receives it
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

MESSAGE="Hello from user_two!"

echo "=== Sending message from user_two to group $GROUP_ID via HTTP ==="

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

echo "[DEBUG] tmpdir: $TMPDIR"
echo "[DEBUG] TOKEN1: ${TOKEN1:0:20}..."
echo "[DEBUG] TOKEN2: ${TOKEN2:0:20}..."
echo "[DEBUG] GROUP_ID: $GROUP_ID"

# Receiver (user_one): authenticate via WebSocket then wait for messages
echo "[DEBUG] starting receiver (user_one)..."
{ echo '{"token":"'"$TOKEN1"'"}'; sleep 5; } \
    | stdbuf -oL websocat ws://localhost:8080/ws > "$TMPDIR/received" 2>"$TMPDIR/recv_err" &
RECV_PID=$!
echo "[DEBUG] receiver PID: $RECV_PID"
sleep 0.5

# Sender (user_two): send message via HTTP POST
echo "[DEBUG] sending message via HTTP..."
SEND_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/new/message" \
    -d "token=$TOKEN2" \
    -d "subject=$GROUP_ID" \
    -d "content=$MESSAGE")
SEND_HTTP_CODE=$(echo "$SEND_RESPONSE" | tail -1)
SEND_BODY=$(echo "$SEND_RESPONSE" | sed '$d')
echo "[DEBUG] send HTTP status: $SEND_HTTP_CODE"
echo "[DEBUG] send response body: $SEND_BODY"

if [[ "$SEND_HTTP_CODE" != "202" ]]; then
    echo "FAIL: HTTP send failed with status $SEND_HTTP_CODE"
    kill $RECV_PID 2>/dev/null
    wait $RECV_PID 2>/dev/null
    exit 1
fi

echo "[DEBUG] waiting 2s for message delivery..."
sleep 2

echo "[DEBUG] killing receiver..."
kill $RECV_PID 2>/dev/null
wait $RECV_PID 2>/dev/null

RECV_ERR=$(cat "$TMPDIR/recv_err")
[[ -n "$RECV_ERR" ]] && echo "[DEBUG] receiver stderr: $RECV_ERR"

RESPONSE=$(cat "$TMPDIR/received")
echo "user_one received: $RESPONSE"

if [[ -z "$RESPONSE" ]]; then
    echo "[DEBUG] EMPTY response - no data received by user_one"
    echo "FAIL: message not received"
    exit 1
fi

if echo "$RESPONSE" | grep -q "$MESSAGE"; then
    echo "PASS"
else
    echo "FAIL: message not received"
    exit 1
fi
