package cn.novalon.gym.manage.app.config;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

import java.lang.reflect.Field;
import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;

@ExtendWith(MockitoExtension.class)
class RateLimitConfigTest {

    @Test
    void testRateLimiterRegistry() throws Exception {
        RateLimitConfig rateLimitConfig = new RateLimitConfig();
        
        setField(rateLimitConfig, "limitForPeriod", 100);
        setField(rateLimitConfig, "limitRefreshPeriod", Duration.ofSeconds(1));
        setField(rateLimitConfig, "timeoutDuration", Duration.ZERO);
        
        RateLimiterRegistry registry = rateLimitConfig.rateLimiterRegistry();
        
        assertThat(registry).isNotNull();
    }

    @Test
    void testApiRateLimiter() throws Exception {
        RateLimitConfig rateLimitConfig = new RateLimitConfig();
        
        setField(rateLimitConfig, "limitForPeriod", 100);
        setField(rateLimitConfig, "limitRefreshPeriod", Duration.ofSeconds(1));
        setField(rateLimitConfig, "timeoutDuration", Duration.ZERO);
        
        RateLimiterRegistry registry = rateLimitConfig.rateLimiterRegistry();
        RateLimiter rateLimiter = rateLimitConfig.apiRateLimiter(registry);
        
        assertThat(rateLimiter).isNotNull();
        assertThat(rateLimiter.getName()).isEqualTo("apiRateLimiter");
    }

    private void setField(Object target, String fieldName, Object value) throws Exception {
        Field field = target.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(target, value);
    }
}