package space.nstart.pcp_tgu_service.service

import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import space.nstart.pcp_tgu_service.config.PlanningProperties

/**
 * Периодически синхронизирует список КА из НСИ; сами окна читает отдельный worker.
 */
@Service
class NsiSyncScheduler(
    private val planningProperties: PlanningProperties,
    private val syncSpacecraftFromNsiUseCase: SyncSpacecraftFromNsiUseCase
) {
    private val log = LoggerFactory.getLogger(javaClass)

    /** Выполняет initial sync, если внешний update включён. */
    @PostConstruct
    fun initSync() {
        if (!planningProperties.externalUpdateEnabled) {
            log.info("External update is disabled. Initial NSI sync skipped.")
            return
        }

        runCatching { syncSpacecraftFromNsiUseCase.syncAllowedSpacecraft() }
            .onFailure { ex -> log.error("Initial NSI sync failed. Application startup will continue.", ex) }
    }

    /** Периодически ставит refresh jobs для active spacecraft из НСИ. */
    @Scheduled(fixedDelayString = "\${planning.external-update-fixed-delay-ms}")
    fun scheduledSync() {
        if (planningProperties.externalUpdateEnabled) {
            syncSpacecraftFromNsiUseCase.syncAllowedSpacecraft()
        }
    }
}
