package space.nstart.pcp.pcp_satellites_service.service

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import space.nstart.pcp.pcp_satellites_service.repository.ComplexPlanRunSatelliteRepository
import space.nstart.pcp.pcp_satellites_service.repository.SatelliteModeRepository
import space.nstart.pcp.pcp_satellites_service.repository.SatelliteModeSnapshotRepository

@Service
class SatelliteDeletedService(
    private val satelliteModeSnapshotRepository: SatelliteModeSnapshotRepository,
    private val satelliteModeRepository: SatelliteModeRepository,
    private val complexPlanRunSatelliteRepository: ComplexPlanRunSatelliteRepository
) {

    private val logger = LoggerFactory.getLogger(this::class.java)

    @Transactional
    fun deleteSatelliteData(satelliteId: Long): SatelliteComplexMissionDeletionSummary {
        val modesDeletedByCascade = satelliteModeRepository.countBySatelliteId(satelliteId)
        val snapshotsBeforeDelete = satelliteModeSnapshotRepository.countBySatelliteId(satelliteId)
        val runLinksBeforeDelete = complexPlanRunSatelliteRepository.countBySatelliteId(satelliteId)

        val snapshotsDeleted = satelliteModeSnapshotRepository.deleteAllBySatelliteId(satelliteId)
        val runLinksDeleted = complexPlanRunSatelliteRepository.deleteAllBySatelliteId(satelliteId)
        val summary = SatelliteComplexMissionDeletionSummary(
            satelliteId = satelliteId,
            snapshotsDeleted = snapshotsDeleted,
            modesDeletedByCascade = modesDeletedByCascade,
            runLinksDeleted = runLinksDeleted
        )

        logger.info(
            "Deleted complex mission data for satellite: satelliteId={}, snapshotsDeleted={}, snapshotsBeforeDelete={}, modesDeletedByCascade={}, runLinksDeleted={}, runLinksBeforeDelete={}",
            summary.satelliteId,
            summary.snapshotsDeleted,
            snapshotsBeforeDelete,
            summary.modesDeletedByCascade,
            summary.runLinksDeleted,
            runLinksBeforeDelete
        )
        return summary
    }
}

data class SatelliteComplexMissionDeletionSummary(
    val satelliteId: Long,
    val snapshotsDeleted: Long,
    val modesDeletedByCascade: Long,
    val runLinksDeleted: Long
)
