package com.mosquito.project.service;

import com.mosquito.project.config.TestCacheConfig;
import com.mosquito.project.domain.Activity;
import com.mosquito.project.dto.CreateActivityRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Import;

import java.time.ZonedDateTime;
import java.util.Objects;

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

@SpringBootTest
@Import({TestCacheConfig.class})
@org.springframework.test.context.TestPropertySource(properties = {
    "spring.flyway.enabled=false",
    "spring.jpa.hibernate.ddl-auto=create-drop"
})
class ActivityServiceCacheTest {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private CacheManager cacheManager;

    @AfterEach
    void tearDown() {
        Objects.requireNonNull(cacheManager.getCache("leaderboards")).clear();
    }

    @Test
    void whenGetLeaderboardIsCalledTwice_thenSecondCallIsFromCache() {
        // Arrange
        CreateActivityRequest createRequest = new CreateActivityRequest();
        createRequest.setName("Cached Activity");
        createRequest.setStartTime(ZonedDateTime.now());
        createRequest.setEndTime(ZonedDateTime.now().plusDays(1));
        Activity activity = activityService.createActivity(createRequest);
        Long activityId = activity.getId();

        // Act: First call
        activityService.getLeaderboard(activityId);

        // Assert: Check that the cache contains the entry
        assertNotNull(Objects.requireNonNull(cacheManager.getCache("leaderboards")).get(activityId));

        // Act: Second call
        activityService.getLeaderboard(activityId);
    }
}
