package at.procon.ted.startup;

import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import at.procon.ted.config.TedProcessorProperties;
import at.procon.ted.repair.TedPackageRepairService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Optional startup runner that repairs / re-imports incomplete legacy TED packages.
 */
@Component
@ConditionalOnRuntimeMode(RuntimeMode.LEGACY)
@RequiredArgsConstructor
@Slf4j
@Order(50)
public class TedPackageRepairStartupRunner implements ApplicationRunner {

    private final TedProcessorProperties properties;
    private final TedPackageRepairService repairService;

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

        if (properties.getDownload().isEnabled() && !properties.getRepair().isAllowWhileDownloadEnabled()) {
            throw new IllegalStateException(
                    "ted.repair.enabled=true requires ted.download.enabled=false " +
                            "or ted.repair.allow-while-download-enabled=true to avoid concurrent package processing");
        }

        log.info("Starting legacy TED package repair tool...");
        repairService.repairConfiguredPackages();
    }
}
