#!/bin/bash
set -e

echo "🔥 Testing rate limiting for booking endpoints..."

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

# 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 hold request
make_hold_request() {
    local request_num=$1
    local session_cookie=$2
    
    local response
    response=$(curl -s -w "%{http_code}" \
        -H "Content-Type: application/json" \
        -H "Cookie: $session_cookie" \
        -d "{
            \"event_id\": $EVENT_ID,
            \"seat_ids\": [\"A-01\", \"A-02\"]
        }" \
        "$HOLD_URL" 2>/dev/null)
    
    local status_code="${response: -3}"
    local body="${response%???}"
    
    echo "Request $request_num: HTTP $status_code"
    
    if [ "$status_code" = "429" ]; then
        local retry_after
        retry_after=$(echo "$body" | jq -r '.retry_after // "unknown"' 2>/dev/null || echo "unknown")
        echo "  Rate limited! Retry after: $retry_after seconds"
        return 1
    elif [ "$status_code" = "422" ] || [ "$status_code" = "409" ]; then
        # Expected for repeated attempts (validation errors or conflicts)
        echo "  Expected error (seats may not exist or already held)"
        return 0
    elif [ "$status_code" = "200" ] || [ "$status_code" = "201" ]; then
        echo "  Success"
        return 0
    else
        echo "  Unexpected status: $status_code"
        echo "  Body: $body"
        return 0
    fi
}

# Function to get session cookie
get_session_cookie() {
    # Make a request to get a session cookie
    local cookie_response
    cookie_response=$(curl -s -I -c - "$BASE_URL/api/seats/availability/1" 2>/dev/null | grep -i "set-cookie" | head -n 1)
    
    if [ -n "$cookie_response" ]; then
        echo "$cookie_response" | sed 's/.*: //' | sed 's/;.*//'
    else
        echo "test_session=12345"
    fi
}

# Main test execution
main() {
    echo "🎯 Rate Limiting Test"
    echo "Testing: $HOLD_URL"
    echo ""
    
    if ! check_server; then
        exit 1
    fi
    
    # Get a session cookie
    echo "🍪 Getting session cookie..."
    session_cookie=$(get_session_cookie)
    echo "Using session: $session_cookie"
    echo ""
    
    # Test IP rate limiting (10 requests per minute by default)
    echo "🧪 Testing IP rate limiting (rapid requests)..."
    
    local rate_limited=false
    local requests_made=0
    
    for i in {1..15}; do
        requests_made=$i
        echo -n "Request $i: "
        
        if make_hold_request "$i" "$session_cookie"; then
            echo ""
        else
            echo "Rate limited at request $i"
            rate_limited=true
            break
        fi
        
        # Small delay to avoid overwhelming
        sleep 0.1
    done
    
    if [ "$rate_limited" = true ]; then
        echo ""
        echo "✅ Rate limiting is working! Got rate limited after $requests_made requests"
        
        # Test that we get proper 429 response with headers
        echo ""
        echo "🧪 Testing 429 response format..."
        
        local rate_limit_response
        rate_limit_response=$(curl -s -H "Content-Type: application/json" \
            -H "Cookie: $session_cookie" \
            -d "{\"event_id\": $EVENT_ID, \"seat_ids\": [\"A-03\"]}" \
            "$HOLD_URL" 2>/dev/null)
        
        echo "Rate limit response:"
        echo "$rate_limit_response" | jq . 2>/dev/null || echo "$rate_limit_response"
        
        # Check for required fields
        if echo "$rate_limit_response" | jq -e '.code == "RATE_LIMIT_IP" or .code == "RATE_LIMIT_SESSION"' >/dev/null 2>&1; then
            echo "✅ Proper error code found"
        else
            echo "❌ Missing or incorrect error code"
        fi
        
        if echo "$rate_limit_response" | jq -e '.retry_after' >/dev/null 2>&1; then
            echo "✅ Retry-after field present"
        else
            echo "❌ Missing retry_after field"
        fi
        
    else
        echo ""
        echo "❌ Rate limiting may not be working - made $requests_made requests without being limited"
        echo "Check rate limit configuration in config/booking.php"
    fi
    
    echo ""
    echo "🧪 Testing rate limit headers on successful request..."
    
    # Wait for rate limit to reset
    echo "Waiting 5 seconds for rate limit to potentially reset..."
    sleep 5
    
    # Make one more request to check headers
    local headers_response
    headers_response=$(curl -s -I -H "Content-Type: application/json" \
        -H "Cookie: $session_cookie" \
        -d "{\"event_id\": $EVENT_ID, \"seat_ids\": [\"A-04\"]}" \
        "$HOLD_URL" 2>/dev/null)
    
    echo "Response headers:"
    echo "$headers_response" | grep -i "x-ratelimit\|retry-after" | sed 's/^/  /'
    
    if echo "$headers_response" | grep -qi "x-ratelimit"; then
        echo "✅ Rate limit headers present"
    else
        echo "⚠️  Rate limit headers not found (may be expected if still rate limited)"
    fi
    
    echo ""
    echo "🎉 Rate limiting test completed!"
    echo ""
    echo "Summary:"
    echo "- Rate limiting: $([ "$rate_limited" = true ] && echo "✅ Working" || echo "⚠️  Check configuration")"
    echo "- 429 responses: $([ "$rate_limited" = true ] && echo "✅ Properly formatted" || echo "⚠️  Not tested")"
    echo "- Headers: Check output above"
}

# Run the test
main "$@"
