#!/bin/bash
# Test tiered architecture API endpoints

set -e

BASE_URL="${API_BASE_URL:-http://localhost:8080}"
echo "=== Testing Tiered Architecture API ==="
echo "Base URL: $BASE_URL"
echo ""

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

PASSED=0
FAILED=0

# Test function
test_endpoint() {
    local method=$1
    local endpoint=$2
    local expected_status=$3
    local description=$4
    local data=$5
    
    echo -n "Testing $description... "
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "\n%{http_code}" "$BASE_URL$endpoint" -H "Content-Type: application/json" 2>&1)
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" "$BASE_URL$endpoint" \
            -H "Content-Type: application/json" \
            -d "$data" 2>&1)
    fi
    
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" = "$expected_status" ]; then
        echo -e "${GREEN}✓ PASS${NC} (HTTP $http_code)"
        ((PASSED++))
        return 0
    else
        echo -e "${RED}✗ FAIL${NC} (Expected $expected_status, got $http_code)"
        echo "  Response: $body" | head -c 200
        echo ""
        ((FAILED++))
        return 1
    fi
}

# Test 1: Health check
test_endpoint "GET" "/health" "200" "Health check"

# Test 2: Feature flags (public)
test_endpoint "GET" "/api/v1/features" "200" "Feature flags (public)"

# Test 3: Track 1 - Latest blocks (public)
test_endpoint "GET" "/api/v1/track1/blocks/latest?limit=5" "200" "Track 1: Latest blocks"

# Test 4: Track 1 - Latest transactions (public)
test_endpoint "GET" "/api/v1/track1/txs/latest?limit=5" "200" "Track 1: Latest transactions"

# Test 5: Track 1 - Bridge status (public)
test_endpoint "GET" "/api/v1/track1/bridge/status" "200" "Track 1: Bridge status"

# Test 6: Auth - Request nonce
test_endpoint "POST" "/api/v1/auth/nonce" "200" "Auth: Request nonce" '{"address":"0x1234567890123456789012345678901234567890"}'

# Test 7: Track 2 - Should require auth (401)
test_endpoint "GET" "/api/v1/track2/search?q=test" "401" "Track 2: Requires auth (401)"

# Test 8: Track 3 - Should require auth (401)
test_endpoint "GET" "/api/v1/track3/analytics/flows" "401" "Track 3: Requires auth (401)"

# Test 9: Track 4 - Should require auth (401)
test_endpoint "GET" "/api/v1/track4/operator/bridge/events" "401" "Track 4: Requires auth (401)"

echo ""
echo "=== Test Summary ==="
echo -e "${GREEN}Passed: $PASSED${NC}"
echo -e "${RED}Failed: $FAILED${NC}"
echo ""

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

