package com.cameleer.server.app.alerting.eval;

import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicInteger;

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

class TickCacheTest {

    @Test
    void getOrComputeCachesWithinTick() {
        var cache = new TickCache();
        int n = cache.getOrCompute("k", () -> 42);
        int m = cache.getOrCompute("k", () -> 43);
        assertThat(n).isEqualTo(42);
        assertThat(m).isEqualTo(42); // cached — supplier not called again
    }

    @Test
    void differentKeysDontCollide() {
        var cache = new TickCache();
        int a = cache.getOrCompute("a", () -> 1);
        int b = cache.getOrCompute("b", () -> 2);
        assertThat(a).isEqualTo(1);
        assertThat(b).isEqualTo(2);
    }

    @Test
    void supplierCalledExactlyOncePerKey() {
        var cache = new TickCache();
        AtomicInteger callCount = new AtomicInteger(0);
        for (int i = 0; i < 5; i++) {
            cache.getOrCompute("k", () -> {
                callCount.incrementAndGet();
                return 99;
            });
        }
        assertThat(callCount.get()).isEqualTo(1);
    }
}
