package space.nstart.pcp_tgu_service.service

import org.springframework.stereotype.Service
import org.springframework.transaction.support.TransactionTemplate
import space.nstart.pcp_tgu_service.domain.PlatformCatalogItem
import space.nstart.pcp_tgu_service.repository.SpacecraftSnapshotRepository
import java.time.LocalDateTime
import space.nstart.pcp.pcp_types_lib.utils.UtcDateTimes

/**
 * Синхронизирует разрешённые КА из НСИ в БД и ставит refresh jobs.
 */
@Service
class SyncSpacecraftFromNsiUseCase(
    private val platformService: PlatformService,
    private val spacecraftSnapshotRepository: SpacecraftSnapshotRepository,
    private val visibilityRefreshJobService: VisibilityRefreshJobService,
    private val transactionTemplate: TransactionTemplate
) {
    /** Загружает allowed platforms из НСИ, сохраняет snapshot и coalesce'ит refresh jobs. */
    fun syncAllowedSpacecraft() {
        val allowedPlatforms = platformService.loadAllowedPlatforms()
        transactionTemplate.executeWithoutResult {
            persistAllowedSpacecraft(allowedPlatforms)
        }
    }

    private fun persistAllowedSpacecraft(allowedPlatforms: List<PlatformCatalogItem>) {
        val now = UtcDateTimes.now()
        val allowedSpacecraftIds = allowedPlatforms.mapNotNull { platform -> platform.noradId?.toString() }

        allowedPlatforms.forEach { platform ->
            val noradId = platform.noradId ?: return@forEach
            val spacecraftId = noradId.toString()
            spacecraftSnapshotRepository.upsertFromNsi(
                spacecraftId = spacecraftId,
                noradId = noradId,
                nsiId = platform.nsiId,
                businessKey = platform.businessKey,
                name = platform.name,
                status = platform.status,
                mission = platform.mission,
                // validFrom/validTo приходят как Instant; в naive-поля БД пишем UTC-naive момент.
                validFrom = platform.validFrom?.let { LocalDateTime.ofInstant(it, UtcDateTimes.UTC) },
                validTo = platform.validTo?.let { LocalDateTime.ofInstant(it, UtcDateTimes.UTC) },
                now = now
            )
            visibilityRefreshJobService.enqueue(spacecraftId, noradId, "NSI_SYNC")
        }

        if (allowedSpacecraftIds.isEmpty()) {
            spacecraftSnapshotRepository.deactivateAllActive(now)
        } else {
            spacecraftSnapshotRepository.deactivateMissing(allowedSpacecraftIds, now)
        }
    }
}
