package space.nstart.pcp_tgu_service.service

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import space.nstart.pcp_tgu_service.dto.StationParamsChangedMessage
import space.nstart.pcp_tgu_service.repository.ProcessedPlanDecisionEventRepository
import space.nstart.pcp_tgu_service.repository.SpacecraftSnapshotRepository
import java.time.LocalDateTime
import space.nstart.pcp.pcp_types_lib.utils.UtcDateTimes

/**
 * На изменение параметров станций перезапрашивает ЗРВ у баллистики по всем активным КА.
 *
 * Дальше [VisibilityRefreshWorker] обновит снапшоты, а будущая цепочка пересоберётся
 * через on-demand [PlanProjectionService].
 */
@Service
class HandleStationParamsChangedUseCase(
    private val processedPlanDecisionEventRepository: ProcessedPlanDecisionEventRepository,
    private val spacecraftSnapshotRepository: SpacecraftSnapshotRepository,
    private val visibilityRefreshJobService: VisibilityRefreshJobService
) {
    private val log = LoggerFactory.getLogger(javaClass)

    /** Идемпотентно по eventId; ставит refresh job по всем активным КА. */
    @Transactional
    fun handle(message: StationParamsChangedMessage) {
        val claimed = processedPlanDecisionEventRepository.insertIfAbsent(message.eventId, UtcDateTimes.now()) != 0
        if (!claimed) {
            return
        }

        val active = spacecraftSnapshotRepository.findAllByActiveTrue()
        active.forEach { snapshot ->
            visibilityRefreshJobService.enqueue(snapshot.spacecraftId, snapshot.noradId, REASON)
        }
        log.info(
            "Station params changed (stationId={}): enqueued visibility refresh for {} active spacecraft.",
            message.stationId, active.size
        )
    }

    private companion object {
        const val REASON = "STATION_PARAMS_CHANGED"
    }
}
