package com.ruoyi.common.core.cache;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;

class InMemoryCacheStoreTest
{
    @Test
    void shouldExpireEntryAfterTtl() throws Exception
    {
        InMemoryCacheStore store = new InMemoryCacheStore();
        store.set("captcha_codes:1", "1234", 20, TimeUnit.MILLISECONDS);
        Thread.sleep(40);
        assertNull(store.get("captcha_codes:1"));
    }

    @Test
    void shouldReturnPrefixKeysInSortedOrder()
    {
        InMemoryCacheStore store = new InMemoryCacheStore();
        store.set("login_tokens:a", "A");
        store.set("login_tokens:b", "B");
        store.set("sys_dict:x", "X");
        assertEquals(Set.of("login_tokens:a", "login_tokens:b"), store.keys("login_tokens:*"));
    }

    @Test
    void shouldTrackHitsMissesWritesAndExpiredEntries() throws Exception
    {
        InMemoryCacheStore store = new InMemoryCacheStore();
        store.set("captcha_codes:2", "5678", 20, TimeUnit.MILLISECONDS);
        assertTrue(store.hasKey("captcha_codes:2"));
        assertEquals("5678", store.get("captcha_codes:2"));
        Thread.sleep(40);
        assertNull(store.get("captcha_codes:2"));
        assertFalse(store.hasKey("captcha_codes:2"));

        InMemoryCacheStats stats = store.snapshot();
        assertEquals("IN_MEMORY", stats.cacheType());
        assertEquals("single-instance", stats.mode());
        assertEquals(0, stats.keySize());
        assertEquals(2, stats.hitCount());
        assertEquals(2, stats.missCount());
        assertEquals(1, stats.expiredCount());
        assertEquals(1, stats.writeCount());
    }
}
