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

import at.procon.dip.domain.time.config.TimeDomainProperties;
import at.procon.dip.domain.time.service.LeitstandTimeImportService;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
@ConditionalOnProperty(prefix = "dip.time.leitstand", name = {"enabled", "startup-selective-materialization-enabled"}, havingValue = "true")
@RequiredArgsConstructor
@Slf4j
public class LeitstandTimeSelectiveMaterializationStartupRunner implements ApplicationRunner {

    private final TimeDomainProperties properties;
    private final LeitstandTimeImportService importService;

    @Override
    public void run(ApplicationArguments args) {
        var cfg = properties.getLeitstand();
        boolean rebuildProjection = cfg.isSelectiveMaterializationBuildProjection();
        if (cfg.getSelectiveMaterializationPersonDbk() != null && !cfg.getSelectiveMaterializationPersonDbk().isBlank()) {
            log.info("Starting selective Leitstand TIME materialization for personDbk={} (rebuildProjection={})", cfg.getSelectiveMaterializationPersonDbk(), rebuildProjection);
            int count = importService.materializeCanonicalTimeEntriesForPersonDbk(cfg.getSelectiveMaterializationPersonDbk(), rebuildProjection);
            log.info("Completed selective Leitstand TIME materialization for personDbk={}. Processed {} recordings", cfg.getSelectiveMaterializationPersonDbk(), count);
            return;
        }
        if (cfg.getSelectiveMaterializationPersonNumber() != null) {
            log.info("Starting selective Leitstand TIME materialization for personNumber={} (rebuildProjection={})", cfg.getSelectiveMaterializationPersonNumber(), rebuildProjection);
            int count = importService.materializeCanonicalTimeEntriesForPersonNumber(cfg.getSelectiveMaterializationPersonNumber(), rebuildProjection);
            log.info("Completed selective Leitstand TIME materialization for personNumber={}. Processed {} recordings", cfg.getSelectiveMaterializationPersonNumber(), count);
            return;
        }
        throw new IllegalStateException("dip.time.leitstand.startup-selective-materialization-enabled=true requires either selective-materialization-person-dbk or selective-materialization-person-number");
    }
}
