package gc.mda.signal_batch.batch.listener;

import gc.mda.signal_batch.domain.gis.cache.AreaBoundaryCache;
import gc.mda.signal_batch.domain.vessel.service.VesselPreviousBucketCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.annotation.AfterJob;
import org.springframework.batch.core.annotation.BeforeJob;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 캐시 기반 Track Job 리스너
 *
 * 기존 VesselTrackDataJobListener 대체:
 * - collectDB 데이터 로드 제거 (AisTargetCacheManager로 대체)
 * - Area/Haegu 경계 캐시 갱신 유지
 * - 이전 버킷 캐시 Fallback 플래그 리셋 유지
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "vessel.batch.scheduler.enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor
public class CacheBasedTrackJobListener implements JobExecutionListener {

    private final AreaBoundaryCache areaBoundaryCache;
    private final VesselPreviousBucketCache previousBucketCache;

    @BeforeJob
    public void beforeJob(JobExecution jobExecution) {
        // Area/Haegu 경계 캐시 갱신
        areaBoundaryCache.refresh();
        log.info("Refreshed area boundary cache");

        // 이전 버킷 캐시 Fallback 플래그 리셋
        previousBucketCache.resetFallbackFlag();
        log.info("Reset previous bucket cache fallback flag");

        log.info("Cache-based track job started: startTime={}, endTime={}",
                jobExecution.getJobParameters().getString("startTime"),
                jobExecution.getJobParameters().getString("endTime"));
    }

    @AfterJob
    public void afterJob(JobExecution jobExecution) {
        // DB 조회 통계 출력
        previousBucketCache.logJobStatistics();
        log.debug("Cache-based track job completed");
    }
}
