#!/bin/bash
set -e

echo "🔍 Testing API cache headers..."

# Configuration
BASE_URL=${BASE_URL:-"http://localhost:8000"}
EVENT_ID=${EVENT_ID:-1}
AVAILABILITY_URL="$BASE_URL/api/seats/availability/$EVENT_ID"

# Function to check if server is running
check_server() {
    if ! curl -s --connect-timeout 5 "$BASE_URL" >/dev/null; then
        echo "❌ Server not accessible at $BASE_URL"
        echo "ℹ️  Start the server with: php artisan serve"
        return 1
    fi
    return 0
}

# Function to make request and check headers
check_cache_headers() {
    local url=$1
    local request_num=$2
    
    echo "📡 Request $request_num to $url"
    
    # Make request and capture headers
    local response_headers
    response_headers=$(curl -s -I "$url" 2>/dev/null)
    
    if [ $? -ne 0 ]; then
        echo "❌ Failed to make request to $url"
        return 1
    fi
    
    echo "Headers received:"
    echo "$response_headers" | grep -i "cache\|pragma\|expires\|age" | sed 's/^/  /'
    
    # Check for no-store directive
    if echo "$response_headers" | grep -qi "cache-control.*no-store"; then
        echo "✅ no-store directive found"
    else
        echo "❌ CRITICAL: no-store directive missing!"
        return 1
    fi
    
    # Check for Age header (should not be present)
    if echo "$response_headers" | grep -qi "^age:"; then
        local age_value
        age_value=$(echo "$response_headers" | grep -i "^age:" | cut -d: -f2 | tr -d ' \r\n')
        echo "❌ CRITICAL: Age header found: $age_value (indicates caching)"
        return 1
    else
        echo "✅ No Age header found (no CDN/proxy caching)"
    fi
    
    # Check for Pragma: no-cache
    if echo "$response_headers" | grep -qi "pragma.*no-cache"; then
        echo "✅ Pragma: no-cache found"
    else
        echo "⚠️  Pragma: no-cache missing (optional but recommended)"
    fi
    
    return 0
}

# Main test execution
main() {
    echo "🎯 Cache Header Smoke Test"
    echo "Testing: $AVAILABILITY_URL"
    echo ""
    
    if ! check_server; then
        exit 1
    fi
    
    echo "🧪 Making first request..."
    if ! check_cache_headers "$AVAILABILITY_URL" "1"; then
        echo ""
        echo "💥 CACHE TEST FAILED: First request failed cache header checks"
        exit 1
    fi
    
    echo ""
    echo "🧪 Making second request (should also have no-cache headers)..."
    if ! check_cache_headers "$AVAILABILITY_URL" "2"; then
        echo ""
        echo "💥 CACHE TEST FAILED: Second request failed cache header checks"
        exit 1
    fi
    
    echo ""
    echo "🧪 Testing response consistency..."
    
    # Get response bodies and compare timestamps
    response1=$(curl -s "$AVAILABILITY_URL" 2>/dev/null | jq -r '.data.timestamp' 2>/dev/null || echo "ERROR")
    sleep 1
    response2=$(curl -s "$AVAILABILITY_URL" 2>/dev/null | jq -r '.data.timestamp' 2>/dev/null || echo "ERROR")
    
    if [ "$response1" != "ERROR" ] && [ "$response2" != "ERROR" ]; then
        if [ "$response1" != "$response2" ]; then
            echo "✅ Timestamps differ between requests (no caching)"
        else
            echo "⚠️  Timestamps are identical (may indicate caching or very fast requests)"
        fi
    else
        echo "ℹ️  Could not parse JSON responses for timestamp comparison"
    fi
    
    echo ""
    echo "🎉 Cache header smoke test completed successfully!"
    echo ""
    echo "Summary:"
    echo "- ✅ No-store headers present on both requests"
    echo "- ✅ No Age headers detected"
    echo "- ✅ API responses are not being cached"
}

# Run the test
main "$@"
