package at.procon.eventhub.importing;

import at.procon.eventhub.dto.AcquisitionStrategy;
import at.procon.eventhub.dto.ImportMode;
import at.procon.eventhub.dto.ImportScopeDto;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
public class ImportChunkPlanner {

    public List<ImportTimeChunkDto> chunksFor(ImportRunRequest request, int defaultChunkDays) {
        ImportScopeDto scope = request.importScope();
        OffsetDateTime from = scope == null ? null : scope.occurredFrom();
        OffsetDateTime to = scope == null ? null : scope.occurredTo();

        if (request.mode() == ImportMode.INCREMENTAL_UPDATE
                && isWatermarkStrategy(request.acquisitionStrategy())) {
            return List.of(new ImportTimeChunkDto(1, from, to));
        }

        if (from == null || to == null) {
            return List.of(new ImportTimeChunkDto(1, from, to));
        }

        List<ImportTimeChunkDto> chunks = new ArrayList<>();
        int days = Math.max(1, defaultChunkDays);
        OffsetDateTime cursor = from;
        int sequence = 1;
        while (cursor.isBefore(to)) {
            OffsetDateTime next = cursor.plusDays(days);
            if (next.isAfter(to)) {
                next = to;
            }
            chunks.add(new ImportTimeChunkDto(sequence++, cursor, next));
            cursor = next;
        }
        return chunks.isEmpty() ? List.of(new ImportTimeChunkDto(1, from, to)) : chunks;
    }

    private boolean isWatermarkStrategy(AcquisitionStrategy strategy) {
        return strategy == AcquisitionStrategy.SOURCE_PACKAGE_WATERMARK
                || strategy == AcquisitionStrategy.SOURCE_ROW_WATERMARK;
    }
}
