package at.procon.dip.domain.ted.startup;

import at.procon.dip.domain.ted.repository.TedNoticeProjectionRepository;
import at.procon.dip.domain.ted.service.TedNoticeProjectionService;
import at.procon.dip.domain.ted.config.TedProjectionProperties;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import at.procon.ted.repository.ProcurementDocumentRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

/**
 * Optional startup backfill for Phase 3 TED projections.
 */
@Component
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
@RequiredArgsConstructor
@Slf4j
public class TedProjectionStartupRunner implements ApplicationRunner {

    private final TedProjectionProperties properties;
    private final ProcurementDocumentRepository procurementDocumentRepository;
    private final TedNoticeProjectionRepository projectionRepository;
    private final TedNoticeProjectionService projectionService;

    @Override
    public void run(ApplicationArguments args) {
        if (!properties.isEnabled() || !properties.isStartupBackfillEnabled()) {
            return;
        }

        int limit = properties.getStartupBackfillLimit();
        log.info("Phase 3 startup backfill enabled - ensuring TED projections for up to {} documents", limit);

        var page = procurementDocumentRepository.findAll(
                PageRequest.of(0, limit, Sort.by(Sort.Direction.ASC, "createdAt")));

        int synced = 0;
        for (var legacyDocument : page.getContent()) {
            if (projectionRepository.existsByLegacyProcurementDocumentId(legacyDocument.getId())) {
                continue;
            }
            projectionService.registerOrRefreshProjection(legacyDocument);
            synced++;
        }

        log.info("Phase 3 startup backfill completed - synced {} TED projections", synced);
    }
}
