#!/bin/bash
# Individual test script for Concurrency feature
# Run this to test only concurrent operations

set -e  # Exit on errors

GATEWAY_URL="${TEST_SERVER_URL:-http://localhost:3000}"
API_KEY="${TEST_API_KEY:-test-key-ce67dabb0d4e27e3d72877c921b89cae}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo "========================================="
echo "Concurrency Tests"
echo "========================================="
echo ""

CONCURRENT_SUCCESS=0
CONCURRENT_TOTAL=5

echo "--- Creating 5 concurrent requests ---"
for i in {1..5}; do
    RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
        -H "x-api-key: $API_KEY" \
        -H "Content-Type: application/json" \
        -d "{\"name\":\"Concurrent Test $i\",\"input\":{\"index\":$i}}" 2>&1)
    
    if [ -n "$RESPONSE" ] && [ ${#RESPONSE} -gt 50 ]; then
        CONCURRENT_SUCCESS=$((CONCURRENT_SUCCESS + 1))
        if [ -t 1 ]; then
            echo "  Request $i: ${GREEN}✓${NC} (length: ${#RESPONSE})"
        else
            echo "  Request $i: PASSED (length: ${#RESPONSE})"
        fi
    else
        if [ -t 1 ]; then
            echo "  Request $i: ${RED}✗${NC} (length: ${#RESPONSE})"
        else
            echo "  Request $i: FAILED (length: ${#RESPONSE})"
        fi
    fi
done

echo ""
echo "========================================="
echo "Concurrency Test Summary"
echo "========================================="
echo "Successful: $CONCURRENT_SUCCESS/$CONCURRENT_TOTAL"
echo ""

if [ "$CONCURRENT_SUCCESS" -ge 3 ]; then
    echo -e "${GREEN}✓ PASSED${NC} - At least 3 concurrent requests succeeded"
    exit 0
else
    echo -e "${RED}✗ FAILED${NC} - Less than 3 concurrent requests succeeded"
    exit 1
fi

