// Copyright (c) 2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! 缓存单元测试
//!
//! 测试缓存模块的各个组件和边缘情况

use dbnexus::cache::{CacheConfig, CacheKey, CacheManager};
use std::hash::{Hash, Hasher};

/// TEST-CACHE-UNIT-001: 缓存配置默认值测试
#[test]
fn test_cache_config_default() {
    let config = CacheConfig::default();

    assert_eq!(config.max_capacity, 10000);
    assert_eq!(config.default_ttl, 300);
    assert_eq!(config.cleanup_interval, 60);
    assert!(config.enable_stats);
}

/// TEST-CACHE-UNIT-002: 缓存键创建测试
#[test]
fn test_cache_key_creation() {
    let key = CacheKey::new("users", "123");

    // 验证键可以创建
    let key2 = CacheKey::new("users", "123");
    assert_eq!(key, key2);
}

/// TEST-CACHE-UNIT-003: 缓存键相等性测试
#[test]
fn test_cache_key_equality() {
    let key1 = CacheKey::new("users", "123");
    let key2 = CacheKey::new("users", "123");
    let key3 = CacheKey::new("users", "456");

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-004: 缓存键哈希测试
#[test]
fn test_cache_key_hash() {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hash};

    let key1 = CacheKey::new("users", "123");
    let key2 = CacheKey::new("users", "123");

    let hasher = RandomState::new();

    let mut hasher1 = hasher.build_hasher();
    key1.hash(&mut hasher1);
    let hash1 = hasher1.finish();

    let mut hasher2 = hasher.build_hasher();
    key2.hash(&mut hasher2);
    let hash2 = hasher2.finish();

    assert_eq!(hash1, hash2);
}

/// TEST-CACHE-UNIT-005: 缓存键克隆测试
#[test]
fn test_cache_key_clone() {
    let key1 = CacheKey::new("users", "123");
    let key2 = key1.clone();

    assert_eq!(key1, key2);
}

/// TEST-CACHE-UNIT-006: 缓存键调试输出测试
#[test]
fn test_cache_key_debug() {
    let key = CacheKey::new("users", "123");

    let debug_str = format!("{:?}", key);
    assert!(debug_str.contains("users:123"));
}

/// TEST-CACHE-UNIT-007: 缓存键从值创建测试
#[test]
fn test_cache_key_from_value() {
    let key1 = CacheKey::from_value("users", &"test_value");
    let key2 = CacheKey::from_value("users", &"test_value");
    let key3 = CacheKey::from_value("users", &"different_value");

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-008: 缓存键从数值创建测试
#[test]
fn test_cache_key_from_numeric_value() {
    let key1 = CacheKey::from_value("users", &12345);
    let key2 = CacheKey::from_value("users", &12345);
    let key3 = CacheKey::from_value("users", &54321);

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-009: 缓存键从结构体创建测试
#[test]
fn test_cache_key_from_struct_value() {
    #[derive(Hash)]
    struct TestStruct {
        id: u64,
        name: String,
    }

    let value1 = TestStruct {
        id: 1,
        name: "test".to_string(),
    };

    let value2 = TestStruct {
        id: 1,
        name: "test".to_string(),
    };

    let value3 = TestStruct {
        id: 2,
        name: "test".to_string(),
    };

    let key1 = CacheKey::from_value("users", &value1);
    let key2 = CacheKey::from_value("users", &value2);
    let key3 = CacheKey::from_value("users", &value3);

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-010: 缓存键模式匹配精确测试
#[test]
fn test_cache_key_pattern_exact_match() {
    let key = CacheKey::new("users", "123");

    // 精确匹配
    assert!(key.matches_pattern("users:123"));

    // 不匹配
    assert!(!key.matches_pattern("users:456"));
    assert!(!key.matches_pattern("orders:123"));
}

/// TEST-CACHE-UNIT-011: 缓存键模式匹配前缀测试
#[test]
fn test_cache_key_pattern_prefix_match() {
    let key = CacheKey::new("users", "123");

    // 前缀匹配
    assert!(key.matches_pattern("users"));

    // 不匹配
    assert!(!key.matches_pattern("orders"));
}

/// TEST-CACHE-UNIT-012: 缓存键模式匹配通配符测试
#[test]
fn test_cache_key_pattern_wildcard_match() {
    let key1 = CacheKey::new("users", "123");
    let key2 = CacheKey::new("users", "456");
    let key3 = CacheKey::new("orders", "123");

    // 通配符匹配
    assert!(key1.matches_pattern("users:*"));
    assert!(key2.matches_pattern("users:*"));
    assert!(key3.matches_pattern("orders:*"));

    // 不匹配
    assert!(!key1.matches_pattern("orders:*"));
    assert!(!key3.matches_pattern("users:*"));
}

/// TEST-CACHE-UNIT-013: 缓存键模式匹配复杂通配符测试
#[test]
fn test_cache_key_pattern_complex_wildcard() {
    let key1 = CacheKey::new("users", "123");
    let key2 = CacheKey::new("users", "abc");
    let key3 = CacheKey::new("admin", "123");

    // 数字通配符
    assert!(key1.matches_pattern("users:[0-9]*"));

    // 字母通配符
    assert!(key2.matches_pattern("users:[a-z]*"));

    // 不匹配
    assert!(!key1.matches_pattern("users:[a-z]*"));
    assert!(!key3.matches_pattern("users:*"));
}

/// TEST-CACHE-UNIT-014: 缓存统计初始化测试
#[test]
fn test_cache_stats_initialization() {
    let stats = dbnexus::cache::CacheStats::new();

    // 验证统计信息初始化
    assert_eq!(stats.hit_rate(), 0.0);
}

/// TEST-CACHE-UNIT-015: 缓存统计命中率零测试
#[test]
fn test_cache_stats_hit_rate_zero() {
    let stats = dbnexus::cache::CacheStats::new();

    // 没有任何操作时，命中率应该是 0
    assert_eq!(stats.hit_rate(), 0.0);
}

/// TEST-CACHE-UNIT-016: 缓存统计命中率百分百测试
#[test]
fn test_cache_stats_hit_rate_100() {
    let stats = dbnexus::cache::CacheStats::new();

    // 记录 10 次命中
    for _ in 0..10 {
        stats.record_hit();
    }

    // 命中率应该是 100%
    assert_eq!(stats.hit_rate(), 1.0);
}

/// TEST-CACHE-UNIT-017: 缓存统计命中率零测试
#[test]
fn test_cache_stats_hit_rate_0() {
    let stats = dbnexus::cache::CacheStats::new();

    // 记录 10 次未命中
    for _ in 0..10 {
        stats.record_miss();
    }

    // 命中率应该是 0%
    assert_eq!(stats.hit_rate(), 0.0);
}

/// TEST-CACHE-UNIT-018: 缓存统计命中率 50% 测试
#[test]
fn test_cache_stats_hit_rate_50() {
    let stats = dbnexus::cache::CacheStats::new();

    // 记录 5 次命中和 5 次未命中
    for _ in 0..5 {
        stats.record_hit();
        stats.record_miss();
    }

    // 命中率应该是 50%
    let hit_rate = stats.hit_rate();
    assert!((hit_rate - 0.5).abs() < 0.01);
}

/// TEST-CACHE-UNIT-019: 缓存统计计数器测试
#[test]
fn test_cache_stats_counters() {
    let stats = dbnexus::cache::CacheStats::new();

    stats.record_hit();
    stats.record_miss();
    stats.record_set();
    stats.record_delete();
    stats.record_expiration();

    // 验证统计信息被正确记录
    // 注意：我们无法直接访问私有字段，但可以通过 hit_rate 验证
    let hit_rate = stats.hit_rate();
    assert!((hit_rate - 0.5).abs() < 0.01);
}

/// TEST-CACHE-UNIT-020: 缓存管理器创建测试
#[tokio::test]
async fn test_cache_manager_creation() {
    let config = CacheConfig::default();
    let cache = CacheManager::<String>::new(config);

    // 验证缓存管理器创建成功
    assert_eq!(cache.len().await, 0);
    assert!(cache.is_empty().await);
}

/// TEST-CACHE-UNIT-021: 缓存管理器容量测试
#[tokio::test]
async fn test_cache_manager_capacity() {
    let config = CacheConfig {
        max_capacity: 100,
        default_ttl: 60,
        cleanup_interval: 10,
        enable_stats: true,
    };
    let cache = CacheManager::<String>::new(config);

    // 添加 100 个条目
    for i in 0..100 {
        let key = CacheKey::new("users", &i.to_string());
        cache.set(key, format!("Value{}", i)).await;
    }

    // 验证缓存大小不超过容量
    assert!(cache.len().await <= 100);
}

/// TEST-CACHE-UNIT-022: 缓存管理器策略测试
#[tokio::test]
async fn test_cache_manager_strategy() {
    let config = CacheConfig::default();
    let cache = CacheManager::<String>::new(config);

    // 验证缓存管理器可以正常工作
    let key = CacheKey::new("users", "1");
    cache.set(key.clone(), "Value".to_string()).await;
    assert!(cache.get(&key).await.is_some());
}

/// TEST-CACHE-UNIT-023: 缓存管理器统计测试
#[tokio::test]
async fn test_cache_manager_stats() {
    let config = CacheConfig::default();
    let cache = CacheManager::<String>::new(config);

    // 验证统计信息可访问
    let stats = cache.stats();
    assert_eq!(stats.hit_rate(), 0.0);
}

/// TEST-CACHE-UNIT-024: 缓存键特殊字符测试
#[test]
fn test_cache_key_special_characters() {
    let key1 = CacheKey::new("users", "test@example.com");
    let key2 = CacheKey::new("users", "test@example.com");
    let key3 = CacheKey::new("users", "test_other@example.com");

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-025: 缓存键空值测试
#[test]
fn test_cache_key_empty_value() {
    let key = CacheKey::new("users", "");

    // 验证空值键可以创建
    let key2 = CacheKey::new("users", "");
    assert_eq!(key, key2);
}

/// TEST-CACHE-UNIT-026: 缓存键长值测试
#[test]
fn test_cache_key_long_value() {
    let long_value = "a".repeat(1000);
    let key = CacheKey::new("users", &long_value);

    // 验证长值键可以创建
    let key2 = CacheKey::new("users", &long_value);
    assert_eq!(key, key2);
}

/// TEST-CACHE-UNIT-027: 缓存键 Unicode 测试
#[test]
fn test_cache_key_unicode() {
    let key1 = CacheKey::new("users", "用户123");
    let key2 = CacheKey::new("users", "用户123");
    let key3 = CacheKey::new("users", "用户456");

    assert_eq!(key1, key2);
    assert_ne!(key1, key3);
}

/// TEST-CACHE-UNIT-028: 缓存配置自定义测试
#[test]
fn test_cache_config_custom() {
    let config = CacheConfig {
        max_capacity: 500,
        default_ttl: 120,
        cleanup_interval: 30,
        enable_stats: false,
    };

    assert_eq!(config.max_capacity, 500);
    assert_eq!(config.default_ttl, 120);
    assert_eq!(config.cleanup_interval, 30);
    assert!(!config.enable_stats);
}

/// TEST-CACHE-UNIT-029: 缓存键克隆性能测试
#[test]
fn test_cache_key_clone_performance() {
    let key = CacheKey::new("users", "123");

    // 克隆 1000 次
    for _ in 0..1000 {
        let _ = key.clone();
    }

    // 验证克隆操作不会失败
    assert!(true);
}

/// TEST-CACHE-UNIT-030: 缓存键哈希性能测试
#[test]
fn test_cache_key_hash_performance() {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hash};

    let key = CacheKey::new("users", "123");
    let hasher = RandomState::new();

    // 哈希 1000 次
    for _ in 0..1000 {
        let mut h = hasher.build_hasher();
        key.hash(&mut h);
        let _ = h.finish();
    }

    // 验证哈希操作不会失败
    assert!(true);
}
