package gc.mda.signal_batch.batch.job;

import gc.mda.signal_batch.batch.listener.CacheBasedTrackJobListener;
import gc.mda.signal_batch.batch.listener.JobCompletionListener;
import gc.mda.signal_batch.batch.listener.PerformanceOptimizationListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersValidator;
import org.springframework.batch.core.job.DefaultJobParametersValidator;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Slf4j
@Configuration
@Profile("!query")  // query 프로파일에서는 배치 작업 비활성화
@RequiredArgsConstructor
@ConditionalOnProperty(name = "vessel.batch.scheduler.enabled", havingValue = "true", matchIfMissing = true)
public class VesselTrackAggregationJobConfig {
    
    private final JobRepository jobRepository;
    private final VesselTrackStepConfig vesselTrackStepConfig;
    private final AisPositionSyncStepConfig aisPositionSyncStepConfig;
    private final JobCompletionListener jobCompletionListener;
    private final CacheBasedTrackJobListener cacheBasedTrackJobListener;
    private final PerformanceOptimizationListener performanceOptimizationListener;
    
    @Bean
    public Job vesselTrackAggregationJob() {
        return new JobBuilder("vesselTrackAggregationJob", jobRepository)
                .incrementer(new RunIdIncrementer())
                .validator(trackJobParametersValidator())
                .listener(jobCompletionListener)
                .listener(cacheBasedTrackJobListener)
                .listener(performanceOptimizationListener)  // 성능 최적화 리스너 추가
                .start(vesselTrackStepConfig.vesselTrackStep())
                .next(vesselTrackStepConfig.gridTrackSummaryStep())
                .next(vesselTrackStepConfig.areaTrackSummaryStep())
                .next(aisPositionSyncStepConfig.aisPositionSyncStep())
                .build();
    }
    
    @Bean
    public JobParametersValidator trackJobParametersValidator() {
        DefaultJobParametersValidator validator = new DefaultJobParametersValidator();
        validator.setRequiredKeys(new String[]{"startTime", "endTime", "timeBucket"});
        validator.setOptionalKeys(new String[]{"executionTime", "processingDate"});
        return validator;
    }
}