#!/bin/bash
# Comprehensive test suite for all phases (Fixed version)
# 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'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

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

# Test result tracking
FAILED_TEST_NAMES=()

# 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")
        if [ -f /tmp/test_output_$$.log ]; then
            echo "  Error output:"
            head -5 /tmp/test_output_$$.log | sed 's/^/    /'
        fi
        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 --max-time 5 "$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="test-idempotency-$(date +%s)"
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" \
    "[ ! -z \"$IDEMPOTENT_RESPONSE\" ] && echo \"$IDEMPOTENT_RESPONSE\" | grep -q '\"id\"'"

FIRST_RUN_ID=$(echo "$IDEMPOTENT_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

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 '"id":"[^"]*' | cut -d'"' -f4 | head -1)
    
    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 ---"
METRICS_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/metrics" 2>/dev/null)

run_test "Metrics: Prometheus metrics endpoint accessible" \
    "[ ! -z \"$METRICS_RESPONSE\" ]"

run_test "Metrics: Metrics include run metrics" \
    "echo \"$METRICS_RESPONSE\" | grep -q 'runs_created_total\|runs_started_total\|runs_completed_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 '"id":"[^"]*' | cut -d'"' -f4 | head -1)

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 ---"
HEADERS=$(curl -sf --max-time 5 -I "$GATEWAY_URL/health" 2>/dev/null)

run_test "Security: Content-Security-Policy header present" \
    "echo \"$HEADERS\" | grep -qi 'content-security-policy'"

run_test "Security: X-Frame-Options header present" \
    "echo \"$HEADERS\" | grep -qi 'x-frame-options'"

run_test "Security: X-Content-Type-Options header present" \
    "echo \"$HEADERS\" | grep -qi 'x-content-type-options'"

run_test "Security: Server header removed" \
    "! echo \"$HEADERS\" | grep -qi '^server:'"

# Phase 4.2: Error Handling
echo ""
echo "--- Phase 4.2: Error Handling ---"
NOT_FOUND_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/00000000-0000-0000-0000-000000000000" \
    -H "x-api-key: $API_KEY" 2>/dev/null)

run_test "Error Handling: 404 error includes correlation ID" \
    "echo \"$NOT_FOUND_RESPONSE\" | grep -q 'correlationId\|correlation_id\|error'"

VALIDATION_RESPONSE=$(curl -sf --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"input":{}}' 2>/dev/null)

run_test "Error Handling: Validation error includes details" \
    "echo \"$VALIDATION_RESPONSE\" | grep -q 'details\|error\|validation'"

INVALID_ID_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/invalid-id" \
    -H "x-api-key: $API_KEY" 2>/dev/null)

run_test "Error Handling: Error response includes timestamp" \
    "echo \"$INVALID_ID_RESPONSE\" | grep -q 'timestamp\|error'"

# Phase 4.3: Health Checks
echo ""
echo "--- Phase 4.3: Health Checks ---"
HEALTH_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/health" 2>/dev/null)

run_test "Health: Liveness endpoint returns 200" \
    "[ ! -z \"$HEALTH_RESPONSE\" ] && echo \"$HEALTH_RESPONSE\" | grep -q '\"status\"\|status'"

READY_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/ready" 2>/dev/null)

run_test "Health: Readiness endpoint returns 200" \
    "[ ! -z \"$READY_RESPONSE\" ] && echo \"$READY_RESPONSE\" | grep -q 'ready\|status'"

run_test "Health: Readiness includes dependency checks" \
    "echo \"$READY_RESPONSE\" | grep -q 'checks\|database\|redis'"

STARTUP_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/startup" 2>/dev/null)

run_test "Health: Startup endpoint accessible" \
    "[ ! -z \"$STARTUP_RESPONSE\" ]"

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 --max-time 5 -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)

WORKFLOW_RUN_ID=$(echo "$WORKFLOW_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

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

if [ ! -z "$WORKFLOW_RUN_ID" ]; then
    START_WORKFLOW=$(curl -sf --max-time 5 -X POST "$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID/start" \
        -H "x-api-key: $API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"priority":"normal"}' 2>/dev/null)
    
    run_test "E2E: Start run" \
        "echo \"$START_WORKFLOW\" | grep -q 'queued\|success'"
    
    GET_WORKFLOW=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/$WORKFLOW_RUN_ID" \
        -H "x-api-key: $API_KEY" 2>/dev/null)
    
    run_test "E2E: Get run status" \
        "echo \"$GET_WORKFLOW\" | grep -q '\"status\"'"
    
    LIST_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs" \
        -H "x-api-key: $API_KEY" 2>/dev/null)
    
    run_test "E2E: List runs" \
        "echo \"$LIST_RESPONSE\" | grep -q '\"runs\"\|\[\]'"
fi

# Authentication Tests
echo ""
echo "--- Authentication Tests ---"
UNAUTH_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs" 2>/dev/null)

run_test "Auth: API key authentication required" \
    "echo \"$UNAUTH_RESPONSE\" | grep -q '401\|403\|Unauthorized\|error' || [ -z \"$UNAUTH_RESPONSE\" ]"

AUTH_RESPONSE=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" 2>/dev/null)

run_test "Auth: Valid API key works" \
    "[ ! -z \"$AUTH_RESPONSE\" ]"

HEALTH_NO_AUTH=$(curl -sf --max-time 5 "$GATEWAY_URL/health" 2>/dev/null)

run_test "Auth: Health endpoint doesn't require auth" \
    "[ ! -z \"$HEALTH_NO_AUTH\" ]"

# 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 --max-time 2 '$GATEWAY_URL/health' > /dev/null 2>&1; done && true"

# Concurrent Operations
echo ""
echo "--- Concurrent Operations ---"
run_test "Concurrency: Multiple runs can be created concurrently" \
    "for i in {1..5}; do \
        curl -sf --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}}\" > /dev/null 2>&1; \
    done && true"

# Priority Queue
echo ""
echo "--- Priority Queue ---"
PRIORITY_RUN1_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":"Normal Priority","input":{"priority":"normal"}}' 2>/dev/null)

PRIORITY_RUN1=$(echo "$PRIORITY_RUN1_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

PRIORITY_RUN2_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":"High Priority","input":{"priority":"high"}}' 2>/dev/null)

PRIORITY_RUN2=$(echo "$PRIORITY_RUN2_RESPONSE" | grep -o '"id":"[^"]*' | cut -d'"' -f4 | head -1)

if [ ! -z "$PRIORITY_RUN1" ] && [ ! -z "$PRIORITY_RUN2" ]; then
    curl -sf --max-time 5 -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 2>&1
    
    curl -sf --max-time 5 -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 2>&1
    
    sleep 2
    
    STATUS1=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/$PRIORITY_RUN1" \
        -H "x-api-key: $API_KEY" 2>/dev/null)
    
    STATUS2=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/$PRIORITY_RUN2" \
        -H "x-api-key: $API_KEY" 2>/dev/null)
    
    run_test "Priority: Both runs started successfully" \
        "echo \"$STATUS1\" | grep -q '\"status\"' && echo \"$STATUS2\" | grep -q '\"status\"'"
fi

# Error Scenarios
echo ""
echo "--- Error Scenarios ---"
NOT_FOUND_404=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/00000000-0000-0000-0000-000000000000" \
    -H "x-api-key: $API_KEY" 2>/dev/null)

run_test "Errors: Invalid run ID returns 404" \
    "echo \"$NOT_FOUND_404\" | grep -q '404\|not found\|error' || [ -z \"$NOT_FOUND_404\" ]"

INVALID_UUID=$(curl -sf --max-time 5 "$GATEWAY_URL/api/runs/invalid-id" \
    -H "x-api-key: $API_KEY" 2>/dev/null)

run_test "Errors: Invalid UUID format returns 400" \
    "echo \"$INVALID_UUID\" | grep -q '400\|Invalid\|error'"

MISSING_FIELD=$(curl -sf --max-time 5 -X POST "$GATEWAY_URL/api/runs" \
    -H "x-api-key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"input":{}}' 2>/dev/null)

run_test "Errors: Missing required field returns 400" \
    "echo \"$MISSING_FIELD\" | grep -q '400\|validation\|error\|details'"

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 "${YELLOW}Note: Some failures may be expected depending on configuration${NC}"
    echo ""
    exit 1
else
    echo -e "${GREEN}✅ All tests passed!${NC}"
    exit 0
fi

