#!/bin/bash
# Individual test script for Queue feature
# Run this to test only queue functionality

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'

PASSED=0
FAILED=0

echo "========================================="
echo "Queue Tests"
echo "========================================="
echo ""

# Test 1: Create run successfully
echo "--- Test 1: Create run successfully ---"
QUEUE_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":"Queue Test","input":{"test":"queue"}}' 2>&1)

QUEUE_RUN_ID=$(echo "$QUEUE_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$QUEUE_RUN_ID" ]; then
    QUEUE_RUN_ID=$(echo "$QUEUE_RESPONSE" | grep -o '"id":"[a-f0-9-]\{36\}' | cut -d'"' -f4 | head -1)
fi

if [ -n "$QUEUE_RUN_ID" ]; then
    echo -e "${GREEN}✓ PASSED${NC} - Created run with ID: $QUEUE_RUN_ID"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}✗ FAILED${NC} - Could not extract run ID"
    echo "Response: ${QUEUE_RESPONSE:0:200}"
    FAILED=$((FAILED + 1))
    exit 1
fi

# Test 2: Start run (should queue)
echo ""
echo "--- Test 2: Start run (should queue) ---"
START_RESPONSE=$(curl -s --max-time 5 -X POST "$GATEWAY_URL/api/runs/$QUEUE_RUN_ID/start" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"priority":"high"}' 2>&1)

if echo "$START_RESPONSE" | grep -q 'queued\|success'; then
    echo -e "${GREEN}✓ PASSED${NC} - Run started and queued"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}✗ FAILED${NC} - Response doesn't indicate queued/success"
    echo "Response: ${START_RESPONSE:0:200}"
    FAILED=$((FAILED + 1))
fi

# Test 3: Get run status
echo ""
echo "--- Test 3: Get run status ---"
sleep 2
STATUS_RESPONSE=$(curl -s --max-time 5 "$GATEWAY_URL/api/runs/$QUEUE_RUN_ID" \
    -H "x-api-key: $API_KEY" 2>&1)

if [ -n "$STATUS_RESPONSE" ] && [ ${#STATUS_RESPONSE} -gt 50 ]; then
    echo -e "${GREEN}✓ PASSED${NC} - Successfully retrieved run status"
    echo "Status response length: ${#STATUS_RESPONSE}"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}✗ FAILED${NC} - Could not retrieve status"
    echo "Response length: ${#STATUS_RESPONSE}"
    FAILED=$((FAILED + 1))
fi

echo ""
echo "========================================="
echo "Queue Test Summary"
echo "========================================="
echo "Passed: $PASSED"
echo "Failed: $FAILED"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}All queue tests passed!${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed${NC}"
    exit 1
fi

