package cn.novalon.gym.manage.gateway.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.*;

/**
 * GatewayMetrics单元测试
 * 
 * 文件定义：测试网关指标收集器的核心功能
 * 涉及业务：请求统计、性能监控、活跃连接数统计
 * 
 * @author 张翔
 * @date 2026-03-26
 */
class GatewayMetricsTest {

    private MeterRegistry meterRegistry;
    private GatewayMetrics gatewayMetrics;

    @BeforeEach
    void setUp() {
        meterRegistry = new SimpleMeterRegistry();
        gatewayMetrics = new GatewayMetrics(meterRegistry);
    }

    @Test
    void testIncrementTotalRequests() {
        gatewayMetrics.incrementTotalRequests();

        assertEquals(1, gatewayMetrics.getTotalRequests());
    }

    @Test
    void testIncrementSuccessRequests() {
        gatewayMetrics.incrementSuccessRequests();

        assertEquals(1, gatewayMetrics.getSuccessRequests());
    }

    @Test
    void testIncrementFailedRequests() {
        gatewayMetrics.incrementFailedRequests();

        assertEquals(1, gatewayMetrics.getFailedRequests());
    }

    @Test
    void testIncrementActiveConnections() {
        gatewayMetrics.incrementActiveConnections();

        assertEquals(1, gatewayMetrics.getActiveConnections());
    }

    @Test
    void testDecrementActiveConnections() {
        gatewayMetrics.incrementActiveConnections();
        gatewayMetrics.incrementActiveConnections();
        gatewayMetrics.decrementActiveConnections();

        assertEquals(1, gatewayMetrics.getActiveConnections());
    }

    @Test
    void testRecordRequestDuration() {
        gatewayMetrics.recordRequestDuration("/api/users", Duration.ofMillis(100));

        assertNotNull(meterRegistry.find("gateway.request.duration").timer());
    }

    @Test
    void testMultipleIncrements() {
        gatewayMetrics.incrementTotalRequests();
        gatewayMetrics.incrementTotalRequests();
        gatewayMetrics.incrementTotalRequests();

        assertEquals(3, gatewayMetrics.getTotalRequests());
    }
}
