#!/bin/bash

# CORS Test Suite for Ginxsom Blossom Server
# Tests all endpoints for both HTTP and HTTPS protocols
# Validates presence of required CORS headers per BUD-01 specification

set -e

# 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 configuration
HTTP_BASE="http://localhost:9001"
HTTPS_BASE="https://localhost:9443"
SAMPLE_SHA256="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"  # empty string hash
SAMPLE_PUBKEY="0000000000000000000000000000000000000000000000000000000000000001"

# Required CORS headers for BUD-01 compliance
REQUIRED_HEADERS=(
    "Access-Control-Allow-Origin"
    "Access-Control-Allow-Methods" 
    "Access-Control-Allow-Headers"
    "Access-Control-Max-Age"
)

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

echo -e "${BLUE}===========================================${NC}"
echo -e "${BLUE}    GINXSOM CORS TEST SUITE (BUD-01)     ${NC}"
echo -e "${BLUE}===========================================${NC}"
echo ""

# Function to check CORS headers
check_cors_headers() {
    local endpoint="$1"
    local method="$2"
    local protocol="$3"
    local extra_args="$4"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    echo -e "${YELLOW}Testing:${NC} $method $endpoint ($protocol)"
    
    # Make request and capture headers
    if [ "$protocol" = "HTTPS" ]; then
        headers=$(curl -k -s -I -X "$method" $extra_args "$endpoint" 2>/dev/null || echo "CURL_FAILED")
    else
        headers=$(curl -s -I -X "$method" $extra_args "$endpoint" 2>/dev/null || echo "CURL_FAILED")
    fi
    
    if [ "$headers" = "CURL_FAILED" ]; then
        echo -e "  ${RED}✗ FAIL:${NC} Could not connect to $endpoint"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
    
    # Check HTTP response is valid
    if ! echo "$headers" | grep -q "HTTP/"; then
        echo -e "  ${RED}✗ FAIL:${NC} Invalid HTTP response"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
    
    local all_headers_present=true
    local missing_headers=()
    
    # Check each required header
    for header in "${REQUIRED_HEADERS[@]}"; do
        if ! echo "$headers" | grep -qi "^$header:"; then
            all_headers_present=false
            missing_headers+=("$header")
        fi
    done
    
    if [ "$all_headers_present" = true ]; then
        echo -e "  ${GREEN}✓ PASS:${NC} All CORS headers present"
        
        # Verify specific header values
        local origin_header=$(echo "$headers" | grep -i "Access-Control-Allow-Origin:" | head -1 | sed 's/.*: *//')
        if [[ "$origin_header" == *"*"* ]]; then
            echo -e "    ${GREEN}✓${NC} Access-Control-Allow-Origin: $origin_header"
        else
            echo -e "    ${RED}✗${NC} Access-Control-Allow-Origin should be '*', got: $origin_header"
            all_headers_present=false
        fi
        
        # Check for duplicate headers (common CORS issue)
        local origin_count=$(echo "$headers" | grep -ci "Access-Control-Allow-Origin:" || echo "0")
        if [ "$origin_count" -gt 1 ]; then
            echo -e "    ${RED}✗${NC} WARNING: Multiple Access-Control-Allow-Origin headers detected ($origin_count)"
            all_headers_present=false
        fi
        
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "  ${RED}✗ FAIL:${NC} Missing CORS headers: ${missing_headers[*]}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
    
    echo ""
    return 0
}

# Test endpoints for both HTTP and HTTPS
test_endpoint() {
    local path="$1"
    local method="$2"
    local extra_args="$3"
    
    # Test HTTP
    check_cors_headers "$HTTP_BASE$path" "$method" "HTTP" "$extra_args"
    
    # Test HTTPS  
    check_cors_headers "$HTTPS_BASE$path" "$method" "HTTPS" "$extra_args"
}

echo -e "${BLUE}=== TESTING CORE BLOSSOM ENDPOINTS ===${NC}"
echo ""

# 1. OPTIONS preflight tests (most critical for CORS)
echo -e "${YELLOW}--- OPTIONS Preflight Requests ---${NC}"
test_endpoint "/" "OPTIONS"
test_endpoint "/upload" "OPTIONS" 
test_endpoint "/auth" "OPTIONS"
test_endpoint "/health" "OPTIONS"
test_endpoint "/mirror" "OPTIONS"
test_endpoint "/report" "OPTIONS"
test_endpoint "/$SAMPLE_SHA256" "OPTIONS"
test_endpoint "/list/$SAMPLE_PUBKEY" "OPTIONS"
test_endpoint "/api/config" "OPTIONS"

# 2. GET requests
echo -e "${YELLOW}--- GET Requests ---${NC}"
test_endpoint "/" "GET"
test_endpoint "/health" "GET" 
test_endpoint "/auth" "GET"
test_endpoint "/$SAMPLE_SHA256" "GET"
test_endpoint "/list/$SAMPLE_PUBKEY" "GET"
test_endpoint "/api/config" "GET"

# 3. HEAD requests
echo -e "${YELLOW}--- HEAD Requests ---${NC}"
test_endpoint "/" "HEAD"
test_endpoint "/health" "HEAD"
test_endpoint "/$SAMPLE_SHA256" "HEAD"
test_endpoint "/upload" "HEAD"

# 4. PUT requests (will likely fail with 400/401 but should still have CORS)
echo -e "${YELLOW}--- PUT Requests (CORS on Errors) ---${NC}"
test_endpoint "/upload" "PUT" "-H 'Content-Type: text/plain'"
test_endpoint "/mirror" "PUT" "-H 'Content-Type: application/json'"
test_endpoint "/report" "PUT" "-H 'Content-Type: application/json'"
test_endpoint "/api/config" "PUT" "-H 'Content-Type: application/json'"

# 5. DELETE requests
echo -e "${YELLOW}--- DELETE Requests ---${NC}" 
test_endpoint "/$SAMPLE_SHA256" "DELETE"

# 6. Edge cases and variations
echo -e "${YELLOW}--- Edge Cases ---${NC}"
test_endpoint "/nonexistent" "GET"
test_endpoint "/$SAMPLE_SHA256.txt" "GET" 
test_endpoint "/$SAMPLE_SHA256.jpg" "GET"
test_endpoint "/list/invalid_pubkey" "GET"

echo -e "${BLUE}===========================================${NC}"
echo -e "${BLUE}           TEST RESULTS SUMMARY           ${NC}"
echo -e "${BLUE}===========================================${NC}"
echo ""
echo -e "Total Tests: $TOTAL_TESTS"
echo -e "${GREEN}Passed: $PASSED_TESTS${NC}"
echo -e "${RED}Failed: $FAILED_TESTS${NC}"
echo ""

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "${GREEN}🎉 ALL TESTS PASSED! 🎉${NC}"
    echo -e "${GREEN}✅ CORS implementation is BUD-01 compliant${NC}"
    echo -e "${GREEN}✅ All endpoints support cross-origin requests${NC}"
    echo -e "${GREEN}✅ No duplicate header issues detected${NC}"
    echo ""
    exit 0
else
    echo -e "${RED}❌ TESTS FAILED! ❌${NC}"
    echo -e "${RED}⚠️  CORS implementation needs fixes${NC}"
    echo ""
    exit 1
fi