#!/bin/bash
# Script to create the clean test-all-phases.sh file on the server

cat > /opt/4runr/gateway/test-all-phases.sh << 'EOFTEST'
#!/bin/bash
# Comprehensive test suite for all phases
# Tests Phase 1-6 features end-to-end

set +e  # Don't exit on errors, we want to see all test results

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

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Test counters
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Test result tracking
FAILED_TEST_NAMES=()

# Generate a valid UUID v4
generate_uuid() {
    if command -v uuidgen > /dev/null 2>&1; then
        uuidgen
    else
        cat /proc/sys/kernel/random/uuid 2>/dev/null || \
        echo "$(od -x /dev/urandom | head -1 | awk '{OFS="-"; print $2$3,$4,$5,$6,$7$8$9}' | tr '[:upper:]' '[:lower:]')"
    fi
}

# Helper function to run a test
run_test() {
    local test_name="$1"
    local test_command="$2"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    echo -n "Testing: $test_name... "
    
    if eval "$test_command" > /tmp/test_output_$$.log 2>&1; then
        echo -e "${GREEN}✓ PASSED${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        return 0
    else
        echo -e "${RED}✗ FAILED${NC}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        FAILED_TEST_NAMES+=("$test_name")
        echo "  Error output:"
        cat /tmp/test_output_$$.log | sed 's/^/    /'
        return 1
    fi
}

echo "========================================="
echo "4Runr Gateway - Comprehensive Phase Test"
echo "========================================="
echo ""
echo "Gateway URL: $GATEWAY_URL"
echo "API Key: ${API_KEY:0:20}..."
echo ""

# Wait for server to be ready
echo "Waiting for server to be ready..."
for i in {1..30}; do
    if curl -sf "$GATEWAY_URL/health" > /dev/null 2>&1; then
        echo "✓ Server is ready"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "❌ Server is not ready after 30 seconds"
        exit 1
    fi
    sleep 1
done

echo ""
echo "========================================="
echo "Phase 1-3: Core Features"
echo "========================================="
echo ""

# Phase 1: Idempotency
echo "--- Phase 1: Idempotency ---"
IDEMPOTENCY_KEY=$(generate_uuid)
IDEMPOTENT_RESPONSE=$(curl -sf --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"Idempotency Test","input":{"test":"idempotency"}}' 2>/dev/null)

run_test "Idempotency: Create run with idempotency key" \
    "echo \"$IDEMPOTENT_RESPONSE\" | grep -q '\"run\"\|\"success\"'"

FIRST_RUN_ID=$(echo "$IDEMPOTENT_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$FIRST_RUN_ID" ]; then
    FIRST_RUN_ID=$(echo "$IDEMPOTENT_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
fi

if [ ! -z "$FIRST_RUN_ID" ]; then
    SECOND_RESPONSE=$(curl -sf --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
        -H "x-api-key: $API_KEY" \
        -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
        -H "Content-Type: application/json" \
        -d '{"name":"Idempotency Test","input":{"test":"idempotency"}}' 2>/dev/null)
    
    SECOND_RUN_ID=$(echo "$SECOND_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
    if [ -z "$SECOND_RUN_ID" ]; then
        SECOND_RUN_ID=$(echo "$SECOND_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
    fi
    
    run_test "Idempotency: Duplicate request returns same run" \
        "[ ! -z \"$SECOND_RUN_ID\" ] && [ \"$FIRST_RUN_ID\" = \"$SECOND_RUN_ID\" ]"
fi

# Phase 2: Structured Logging & Metrics
echo ""
echo "--- Phase 2: Logging & Metrics ---"
run_test "Metrics: Prometheus metrics endpoint accessible" \
    "curl -sf '$GATEWAY_URL/metrics' | grep -q 'http_request_total'"

run_test "Metrics: Metrics include run metrics" \
    "curl -sf '$GATEWAY_URL/metrics' | grep -q 'runs_created_total'"

# Phase 3: Queue System
echo ""
echo "--- Phase 3: Queue System ---"
QUEUE_RESPONSE=$(curl -sf --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>/dev/null)

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":"[^"]*' | cut -d'"' -f4 | head -1)
fi

run_test "Queue: Create run successfully" \
    "[ ! -z \"$QUEUE_RUN_ID\" ]"

if [ ! -z "$QUEUE_RUN_ID" ]; then
    START_RESPONSE=$(curl -sf --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>/dev/null)
    
    run_test "Queue: Start run (should queue)" \
        "echo \"$START_RESPONSE\" | grep -q 'queued\|success'"
    
    sleep 2
    
    STATUS_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/$QUEUE_RUN_ID" \
        -H "x-api-key: $API_KEY" 2>/dev/null)
    
    run_test "Queue: Run status updated" \
        "echo \"$STATUS_RESPONSE\" | grep -q '\"status\"'"
fi

echo ""
echo "========================================="
echo "Phase 4: Production Hardening"
echo "========================================="
echo ""

# Phase 4.1: Security Headers
echo "--- Phase 4.1: Security Headers ---"
run_test "Security: Content-Security-Policy header present" \
    "curl -sf -I '$GATEWAY_URL/health' | grep -qi 'content-security-policy'"

run_test "Security: X-Frame-Options header present" \
    "curl -sf -I '$GATEWAY_URL/health' | grep -qi 'x-frame-options'"

run_test "Security: X-Content-Type-Options header present" \
    "curl -sf -I '$GATEWAY_URL/health' | grep -qi 'x-content-type-options'"

run_test "Security: Server header removed" \
    "! curl -sf -I '$GATEWAY_URL/health' | grep -qi '^server:'"

# Phase 4.2: Error Handling
echo ""
echo "--- Phase 4.2: Error Handling ---"
run_test "Error Handling: 404 error includes correlation ID" \
    "curl -s '$GATEWAY_URL/api/runs/00000000-0000-0000-0000-000000000000' \
    -H 'x-api-key: $API_KEY' | grep -q 'error'"

run_test "Error Handling: Validation error includes details" \
    "curl -s -X POST '$GATEWAY_URL/api/runs' \
    -H 'x-api-key: $API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{\"input\":{}}' | grep -q 'details'"

run_test "Error Handling: Error response includes timestamp" \
    "curl -s '$GATEWAY_URL/api/runs/invalid-id' \
    -H 'x-api-key: $API_KEY' | grep -q 'timestamp'"

# Phase 4.3: Health Checks
echo ""
echo "--- Phase 4.3: Health Checks ---"
run_test "Health: Liveness endpoint returns 200" \
    "curl -sf '$GATEWAY_URL/health' | grep -q '\"status\"'"

run_test "Health: Readiness endpoint returns 200" \
    "curl -sf '$GATEWAY_URL/ready' | grep -q '\"ready\"'"

run_test "Health: Readiness includes dependency checks" \
    "curl -sf '$GATEWAY_URL/ready' | grep -q '\"checks\"'"

run_test "Health: Startup endpoint accessible" \
    "curl -sf '$GATEWAY_URL/startup' | grep -q '\"started\"'"

echo ""
echo "========================================="
echo "Phase 5: Testing & Validation"
echo "========================================="
echo ""

# Phase 5: Integration Tests
echo "--- Phase 5: Integration Tests ---"
run_test "Integration: Can run integration tests" \
    "cd /opt/4runr/gateway && pnpm test:integration -- simple.test.ts 2>&1 | grep -q 'PASS'"

echo ""
echo "========================================="
echo "End-to-End Workflow Tests"
echo "========================================="
echo ""

# Complete Workflow
echo "--- Complete Run Workflow ---"
WORKFLOW_RESPONSE=$(curl -sf -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"E2E Workflow Test","input":{"test":"workflow"}}' 2>/dev/null)

# Extract run ID - try multiple patterns
WORKFLOW_RUN_ID=$(echo "$WORKFLOW_RESPONSE" | grep -o '"run"[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$WORKFLOW_RUN_ID" ]; then
    # Try simpler pattern
    WORKFLOW_RUN_ID=$(echo "$WORKFLOW_RESPONSE" | grep -o '"id":"[a-f0-9-]\{36\}' | cut -d'"' -f4 | head -1)
fi

run_test "E2E: Create run" \
    "[ ! -z \"$WORKFLOW_RUN_ID\" ]"

if [ ! -z "$WORKFLOW_RUN_ID" ]; then
    run_test "E2E: Start run" \
        "curl -sf -X POST '$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID/start' \
        -H 'x-api-key: $API_KEY' \
        -H 'Content-Type: application/json' \
        -d '{\"priority\":\"normal\"}' | grep -q '\"queued\"'"
    
    run_test "E2E: Get run status" \
        "curl -sf '$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID' \
        -H 'x-api-key: $API_KEY' | grep -q '\"status\"'"
    
    run_test "E2E: List runs" \
        "curl -sf '$GATEWAY_URL/api/runs' \
        -H 'x-api-key: $API_KEY' | grep -q '\"runs\"'"
fi

# Authentication Tests
echo ""
echo "--- Authentication Tests ---"
run_test "Auth: API key authentication required" \
    "curl -sf '$GATEWAY_URL/api/runs' | grep -q '401\|403\|Unauthorized'"

run_test "Auth: Valid API key works" \
    "curl -sf '$GATEWAY_URL/api/runs' \
    -H 'x-api-key: $API_KEY' | grep -q '\"runs\"'"

run_test "Auth: Health endpoint doesn't require auth" \
    "curl -sf '$GATEWAY_URL/health' | grep -q '\"status\"'"

# Rate Limiting Tests
echo ""
echo "--- Rate Limiting Tests ---"
run_test "Rate Limit: Health endpoint bypasses rate limiting" \
    "for i in {1..20}; do curl -sf '$GATEWAY_URL/health' > /dev/null; done && true"

# Concurrent Operations
echo ""
echo "--- Concurrent Operations ---"
CONCURRENT_SUCCESS=0
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>/dev/null)
    if [ ! -z "$RESPONSE" ] && (echo "$RESPONSE" | grep -q '"run"\|"success"'); then
        CONCURRENT_SUCCESS=$((CONCURRENT_SUCCESS + 1))
    fi
done

run_test "Concurrency: Multiple runs can be created concurrently" \
    "[ $CONCURRENT_SUCCESS -ge 3 ]"

# Priority Queue
echo ""
echo "--- Priority Queue ---"
PRIORITY_RUN1_RESPONSE=$(curl -sf -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"Normal Priority","input":{"priority":"normal"}}' 2>/dev/null)

PRIORITY_RUN1=$(echo "$PRIORITY_RUN1_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$PRIORITY_RUN1" ]; then
    PRIORITY_RUN1=$(echo "$PRIORITY_RUN1_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
fi

PRIORITY_RUN2_RESPONSE=$(curl -sf -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"High Priority","input":{"priority":"high"}}' 2>/dev/null)

PRIORITY_RUN2=$(echo "$PRIORITY_RUN2_RESPONSE" | grep -o '"run":{[^}]*"id":"[^"]*' | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
if [ -z "$PRIORITY_RUN2" ]; then
    PRIORITY_RUN2=$(echo "$PRIORITY_RUN2_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)
fi

if [ ! -z "$PRIORITY_RUN1" ] && [ ! -z "$PRIORITY_RUN2" ]; then
    curl -sf -X POST "$GATEWAY_URL/api/runs/$PRIORITY_RUN1/start" \
        -H "x-api-key: $API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"priority":"normal"}' > /dev/null
    
    curl -sf -X POST "$GATEWAY_URL/api/runs/$PRIORITY_RUN2/start" \
        -H "x-api-key: $API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"priority":"high"}' > /dev/null
    
    sleep 2
    
    run_test "Priority: Both runs started successfully" \
        "curl -sf '$GATEWAY_URL/api/runs/$PRIORITY_RUN1' -H 'x-api-key: $API_KEY' | grep -q '\"status\"' && \
         curl -sf '$GATEWAY_URL/api/runs/$PRIORITY_RUN2' -H 'x-api-key: $API_KEY' | grep -q '\"status\"'"
fi

# Error Scenarios
echo ""
echo "--- Error Scenarios ---"
run_test "Errors: Invalid run ID returns 404" \
    "curl -s '$GATEWAY_URL/api/runs/00000000-0000-0000-0000-000000000000' \
    -H 'x-api-key: $API_KEY' | grep -q 'error'"

run_test "Errors: Invalid UUID format returns 400" \
    "curl -s '$GATEWAY_URL/api/runs/invalid-id' \
    -H 'x-api-key: $API_KEY' | grep -q 'error'"

run_test "Errors: Missing required field returns 400" \
    "curl -s -X POST '$GATEWAY_URL/api/runs' \
    -H 'x-api-key: $API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{\"input\":{}}' | grep -q 'error'"

echo ""
echo "========================================="
echo "Test Summary"
echo "========================================="
echo ""
echo "Total Tests: $TOTAL_TESTS"
echo -e "${GREEN}Passed: $PASSED_TESTS${NC}"
echo -e "${RED}Failed: $FAILED_TESTS${NC}"
echo ""

if [ $FAILED_TESTS -gt 0 ]; then
    echo -e "${RED}Failed Tests:${NC}"
    for test_name in "${FAILED_TEST_NAMES[@]}"; do
        echo "  - $test_name"
    done
    echo ""
    echo -e "${RED}❌ Some tests failed. Please review the errors above.${NC}"
    exit 1
else
    echo -e "${GREEN}✅ All tests passed!${NC}"
    exit 0
fi
EOFTEST

chmod +x /opt/4runr/gateway/test-all-phases.sh
echo "✓ Clean test-all-phases.sh created successfully"

