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

//! Health 模块测试

#![cfg(feature = "health-check")]

#[path = "../../common/mod.rs"]
mod common;

/// TEST-H-001: 健康检查测试
#[tokio::test]
async fn test_health_check() {
    use dbnexus::{DbConfig, DbConfigBuilder, DbPool};

    let db_url = "sqlite::memory:".to_string();
    let config = DbConfigBuilder::new()
        .url(&db_url)
        .admin_role("admin")
        .build()
        .expect("Failed to build config");

    let pool = DbPool::with_config(config).await.expect("Failed to create pool");

    // 获取一个连接来初始化连接池（使用 admin 角色）
    let _session: dbnexus::Session = pool.with_role("admin").await.expect("Failed to get session");
    drop(_session);

    // 执行健康检查（返回 bool）
    let is_healthy = pool.health_check().await;

    assert!(is_healthy, "Health check should return true for a healthy pool");
}

/// TEST-H-002: 健康指标测试
#[tokio::test]
async fn test_health_metrics() {
    use dbnexus::health::{PoolHealthMetrics, PoolSnapshot};

    // 创建健康指标
    let metrics = PoolHealthMetrics::new();

    // 记录一些操作
    metrics.record_connection_created();
    metrics.record_connection_created();
    metrics.record_connection_failed();

    // 添加空闲连接
    metrics.decrement_active();
    metrics.increment_idle().await;

    // 获取快照
    let snapshot = metrics.snapshot();

    assert_eq!(snapshot.total, 2);
    assert_eq!(snapshot.active, 1);
    assert_eq!(snapshot.idle, 1);
    assert_eq!(snapshot.created, 2);
    assert_eq!(snapshot.failed, 1);

    // 检查是否健康（有空闲连接）
    assert!(metrics.is_healthy());
}

/// TEST-H-003: 熔断器配置测试
#[tokio::test]
async fn test_circuit_breaker_config() {
    use dbnexus::health::{CircuitBreaker, CircuitBreakerConfig, CircuitBreakerState};

    // 配置熔断器
    let circuit_config = CircuitBreakerConfig {
        failure_threshold: 5,
        success_threshold: 2,
        timeout_ms: 30000,
        window_size: 10,
    };

    let breaker = CircuitBreaker::new(circuit_config);

    // 获取熔断器状态
    let circuit_state = breaker.state().await;

    assert_eq!(circuit_state, CircuitBreakerState::Closed);

    // 测试失败阈值
    for _ in 0..5 {
        breaker.record_failure().await;
    }

    // 应该转换为打开状态
    let state_after_failures = breaker.state().await;
    assert_eq!(state_after_failures, CircuitBreakerState::Open);
}
