package gc.mda.kcg.domain.analysis;

import gc.mda.kcg.config.CacheConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
@RequiredArgsConstructor
public class VesselAnalysisService {

    private static final int RECENT_MINUTES = 10;

    private final VesselAnalysisResultRepository repository;
    private final CacheManager cacheManager;

    /**
     * 최근 10분 내 분석 결과를 반환한다. Caffeine 캐시(TTL 5분) 적용.
     */
    @SuppressWarnings("unchecked")
    public List<VesselAnalysisDto> getLatestResults() {
        Cache cache = cacheManager.getCache(CacheConfig.VESSEL_ANALYSIS);
        if (cache != null) {
            Cache.ValueWrapper wrapper = cache.get("data");
            if (wrapper != null) {
                return (List<VesselAnalysisDto>) wrapper.get();
            }
        }

        Instant since = Instant.now().minus(RECENT_MINUTES, ChronoUnit.MINUTES);
        List<VesselAnalysisDto> results = repository.findByTimestampAfter(since)
                .stream()
                .map(VesselAnalysisDto::from)
                .toList();

        if (cache != null) {
            cache.put("data", results);
        }

        return results;
    }
}
