package com.njcn.rdms.module.system.framework.cache;

import com.njcn.rdms.framework.test.core.ut.BaseMockitoUnitTest;
import com.njcn.rdms.module.system.dal.redis.RedisKeyConstants;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.ApplicationArguments;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class PermissionCacheStartupCleanerTest extends BaseMockitoUnitTest {

    @Mock
    private CacheManager cacheManager;
    @Mock
    private Cache roleCache;
    @Mock
    private Cache userRoleCache;
    @Mock
    private Cache menuRoleCache;
    @Mock
    private Cache permissionMenuCache;

    @InjectMocks
    private PermissionCacheStartupCleaner cleaner;

    @Test
    void run_shouldClearPermissionRelatedCaches() throws Exception {
        when(cacheManager.getCache(RedisKeyConstants.ROLE)).thenReturn(roleCache);
        when(cacheManager.getCache(RedisKeyConstants.USER_ROLE_ID_LIST)).thenReturn(userRoleCache);
        when(cacheManager.getCache(RedisKeyConstants.MENU_ROLE_ID_LIST)).thenReturn(menuRoleCache);
        when(cacheManager.getCache(RedisKeyConstants.PERMISSION_MENU_ID_LIST)).thenReturn(permissionMenuCache);

        cleaner.run(mock(ApplicationArguments.class));

        verify(roleCache).clear();
        verify(userRoleCache).clear();
        verify(menuRoleCache).clear();
        verify(permissionMenuCache).clear();
    }

    @Test
    void run_shouldIgnoreMissingCaches() {
        when(cacheManager.getCache(RedisKeyConstants.ROLE)).thenReturn(roleCache);

        assertDoesNotThrow(() -> cleaner.run(mock(ApplicationArguments.class)));

        verify(roleCache).clear();
    }

}
