#!/bin/bash

# SEEN Dragonfly Cache Integration Test
# Tests all cache operations to verify full functionality

set -e

CACHE_ADDR="localhost:6379"

echo "🔥 SEEN Dragonfly Cache Test Suite"
echo "===================================="
echo ""

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

success() {
    echo -e "${GREEN}✓${NC} $1"
}

error() {
    echo -e "${RED}✗${NC} $1"
}

info() {
    echo -e "${YELLOW}→${NC} $1"
}

section() {
    echo -e "${BLUE}▶${NC} $1"
}

# Check if redis-cli is available
if ! command -v redis-cli &> /dev/null; then
    error "redis-cli not found. Please install redis-tools."
    exit 1
fi

# Test basic connectivity
test_connectivity() {
    section "Testing Dragonfly Connectivity..."
    
    info "PING"
    if redis-cli -h localhost -p 6379 PING | grep -q "PONG"; then
        success "Dragonfly is responsive"
    else
        error "Dragonfly is not responding"
        exit 1
    fi
    
    echo ""
}

# Test basic operations
test_basic_operations() {
    section "Testing Basic Cache Operations..."
    
    # SET
    info "SET test:key 'test-value'"
    redis-cli -h localhost -p 6379 SET "test:key" "test-value" > /dev/null
    success "SET operation successful"
    
    # GET
    info "GET test:key"
    VALUE=$(redis-cli -h localhost -p 6379 GET "test:key")
    if [ "$VALUE" = "test-value" ]; then
        success "GET operation successful"
    else
        error "GET operation failed"
    fi
    
    # EXISTS
    info "EXISTS test:key"
    if redis-cli -h localhost -p 6379 EXISTS "test:key" | grep -q "1"; then
        success "EXISTS operation successful"
    else
        error "EXISTS operation failed"
    fi
    
    # DEL
    info "DEL test:key"
    redis-cli -h localhost -p 6379 DEL "test:key" > /dev/null
    success "DEL operation successful"
    
    echo ""
}

# Test TTL operations
test_ttl_operations() {
    section "Testing TTL Operations..."
    
    # SETEX
    info "SETEX test:ttl 5 'expires-soon'"
    redis-cli -h localhost -p 6379 SETEX "test:ttl" 5 "expires-soon" > /dev/null
    success "SETEX operation successful"
    
    # TTL
    info "TTL test:ttl"
    TTL=$(redis-cli -h localhost -p 6379 TTL "test:ttl")
    if [ "$TTL" -gt 0 ] && [ "$TTL" -le 5 ]; then
        success "TTL operation successful (${TTL}s remaining)"
    else
        error "TTL operation failed"
    fi
    
    # EXPIRE
    info "EXPIRE test:ttl 10"
    redis-cli -h localhost -p 6379 EXPIRE "test:ttl" 10 > /dev/null
    success "EXPIRE operation successful"
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "test:ttl" > /dev/null
    
    echo ""
}

# Test atomic operations
test_atomic_operations() {
    section "Testing Atomic Operations..."
    
    # INCR
    info "INCR test:counter"
    COUNT=$(redis-cli -h localhost -p 6379 INCR "test:counter")
    if [ "$COUNT" = "1" ]; then
        success "INCR operation successful"
    else
        error "INCR operation failed"
    fi
    
    # INCRBY
    info "INCRBY test:counter 5"
    COUNT=$(redis-cli -h localhost -p 6379 INCRBY "test:counter" 5)
    if [ "$COUNT" = "6" ]; then
        success "INCRBY operation successful"
    else
        error "INCRBY operation failed"
    fi
    
    # SETNX (lock simulation)
    info "SETNX test:lock 'owner-123'"
    ACQUIRED=$(redis-cli -h localhost -p 6379 SETNX "test:lock" "owner-123")
    if [ "$ACQUIRED" = "1" ]; then
        success "SETNX operation successful (lock acquired)"
    else
        error "SETNX operation failed"
    fi
    
    # Try to acquire again (should fail)
    info "SETNX test:lock 'owner-456' (should fail)"
    ACQUIRED=$(redis-cli -h localhost -p 6379 SETNX "test:lock" "owner-456")
    if [ "$ACQUIRED" = "0" ]; then
        success "SETNX correctly prevented duplicate lock"
    else
        error "SETNX allowed duplicate lock"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "test:counter" "test:lock" > /dev/null
    
    echo ""
}

# Test JSON operations
test_json_operations() {
    section "Testing JSON Storage..."
    
    # Store JSON
    info "SET test:json '{\"name\":\"test\",\"value\":123}'"
    redis-cli -h localhost -p 6379 SET "test:json" '{"name":"test","value":123}' > /dev/null
    success "JSON storage successful"
    
    # Retrieve JSON
    info "GET test:json"
    JSON=$(redis-cli -h localhost -p 6379 GET "test:json")
    if echo "$JSON" | grep -q "test"; then
        success "JSON retrieval successful"
    else
        error "JSON retrieval failed"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "test:json" > /dev/null
    
    echo ""
}

# Test bulk operations
test_bulk_operations() {
    section "Testing Bulk Operations..."
    
    # MSET
    info "MSET test:key1 'value1' test:key2 'value2' test:key3 'value3'"
    redis-cli -h localhost -p 6379 MSET "test:key1" "value1" "test:key2" "value2" "test:key3" "value3" > /dev/null
    success "MSET operation successful"
    
    # MGET
    info "MGET test:key1 test:key2 test:key3"
    VALUES=$(redis-cli -h localhost -p 6379 MGET "test:key1" "test:key2" "test:key3")
    if echo "$VALUES" | grep -q "value1" && echo "$VALUES" | grep -q "value2" && echo "$VALUES" | grep -q "value3"; then
        success "MGET operation successful"
    else
        error "MGET operation failed"
    fi
    
    # DEL multiple keys
    info "DEL test:key1 test:key2 test:key3"
    redis-cli -h localhost -p 6379 DEL "test:key1" "test:key2" "test:key3" > /dev/null
    success "Bulk DEL operation successful"
    
    echo ""
}

# Test pattern operations
test_pattern_operations() {
    section "Testing Pattern Operations..."
    
    # Create test keys
    redis-cli -h localhost -p 6379 SET "seen:session:123" "data1" > /dev/null
    redis-cli -h localhost -p 6379 SET "seen:session:456" "data2" > /dev/null
    redis-cli -h localhost -p 6379 SET "seen:user:789" "data3" > /dev/null
    
    # KEYS pattern
    info "KEYS seen:session:*"
    KEYS=$(redis-cli -h localhost -p 6379 KEYS "seen:session:*")
    KEY_COUNT=$(echo "$KEYS" | wc -l)
    if [ "$KEY_COUNT" -ge 2 ]; then
        success "KEYS pattern matching successful (found $KEY_COUNT keys)"
    else
        error "KEYS pattern matching failed"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "seen:session:123" "seen:session:456" "seen:user:789" > /dev/null
    
    echo ""
}

# Test cache statistics
test_statistics() {
    section "Testing Cache Statistics..."
    
    # DBSIZE
    info "DBSIZE"
    SIZE=$(redis-cli -h localhost -p 6379 DBSIZE)
    success "Database size: $SIZE keys"
    
    # INFO memory
    info "INFO memory"
    MEMORY=$(redis-cli -h localhost -p 6379 INFO memory | grep "used_memory_human" | cut -d: -f2 | tr -d '\r')
    success "Memory usage: $MEMORY"
    
    # INFO stats
    info "INFO stats"
    TOTAL_COMMANDS=$(redis-cli -h localhost -p 6379 INFO stats | grep "total_commands_processed" | cut -d: -f2 | tr -d '\r')
    success "Total commands processed: $TOTAL_COMMANDS"
    
    echo ""
}

# Test session cache pattern
test_session_pattern() {
    section "Testing Session Cache Pattern..."
    
    # Simulate session storage
    SESSION_ID="session-test-123"
    SESSION_DATA='{"sessionId":"session-test-123","userId":"user-456","expiresAt":"2026-04-07T00:00:00Z"}'
    
    info "Store session: seen:session:$SESSION_ID"
    redis-cli -h localhost -p 6379 SETEX "seen:session:$SESSION_ID" 3600 "$SESSION_DATA" > /dev/null
    success "Session stored with 1 hour TTL"
    
    info "Retrieve session"
    RETRIEVED=$(redis-cli -h localhost -p 6379 GET "seen:session:$SESSION_ID")
    if echo "$RETRIEVED" | grep -q "user-456"; then
        success "Session retrieved successfully"
    else
        error "Session retrieval failed"
    fi
    
    info "Check session TTL"
    TTL=$(redis-cli -h localhost -p 6379 TTL "seen:session:$SESSION_ID")
    if [ "$TTL" -gt 0 ]; then
        success "Session TTL: ${TTL}s"
    else
        error "Session TTL check failed"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "seen:session:$SESSION_ID" > /dev/null
    
    echo ""
}

# Test download progress pattern
test_download_pattern() {
    section "Testing Download Progress Pattern..."
    
    # Simulate download progress
    JOB_ID="job-test-789"
    PROGRESS_DATA='{"jobId":"job-test-789","status":"downloading","progressPercent":45,"bytesDownloaded":450000000,"bytesTotal":1000000000}'
    
    info "Store download progress: seen:download:job:$JOB_ID"
    redis-cli -h localhost -p 6379 SETEX "seen:download:job:$JOB_ID" 30 "$PROGRESS_DATA" > /dev/null
    success "Download progress stored with 30s TTL"
    
    info "Retrieve download progress"
    RETRIEVED=$(redis-cli -h localhost -p 6379 GET "seen:download:job:$JOB_ID")
    if echo "$RETRIEVED" | grep -q "downloading"; then
        success "Download progress retrieved successfully"
    else
        error "Download progress retrieval failed"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "seen:download:job:$JOB_ID" > /dev/null
    
    echo ""
}

# Test rate limiting pattern
test_rate_limit_pattern() {
    section "Testing Rate Limit Pattern..."
    
    USER_ID="user-ratelimit-test"
    LIMIT_KEY="seen:ratelimit:$USER_ID:api-call"
    
    info "Simulate API calls (limit: 5 per minute)"
    for i in {1..5}; do
        COUNT=$(redis-cli -h localhost -p 6379 INCR "$LIMIT_KEY")
        if [ "$i" -eq 1 ]; then
            redis-cli -h localhost -p 6379 EXPIRE "$LIMIT_KEY" 60 > /dev/null
        fi
        echo "  Call $i: count=$COUNT"
    done
    success "Rate limit counter working"
    
    info "Check if limit exceeded"
    COUNT=$(redis-cli -h localhost -p 6379 GET "$LIMIT_KEY")
    if [ "$COUNT" -eq 5 ]; then
        success "Rate limit at threshold: $COUNT/5"
    else
        error "Rate limit count incorrect: $COUNT"
    fi
    
    # Cleanup
    redis-cli -h localhost -p 6379 DEL "$LIMIT_KEY" > /dev/null
    
    echo ""
}

# Run all tests
test_connectivity
test_basic_operations
test_ttl_operations
test_atomic_operations
test_json_operations
test_bulk_operations
test_pattern_operations
test_statistics
test_session_pattern
test_download_pattern
test_rate_limit_pattern

echo "===================================="
echo "✅ All cache tests completed!"
echo ""
echo "Summary:"
echo "  - Basic operations: working"
echo "  - TTL management: working"
echo "  - Atomic operations: working"
echo "  - JSON storage: working"
echo "  - Bulk operations: working"
echo "  - Pattern matching: working"
echo "  - Statistics: working"
echo "  - Session caching: working"
echo "  - Download progress: working"
echo "  - Rate limiting: working"
echo ""
echo "🔥 Dragonfly DB is fully integrated and functional!"
