package space.nstart.pcp.complan.service

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import space.nstart.pcp.complan.db.repository.DynamicPlanRouteRepository
import space.nstart.pcp.complan.db.repository.DynamicPlanRunRepository

@Service
class SatelliteDeletedService(
    private val runRepository: DynamicPlanRunRepository,
    private val routeRepository: DynamicPlanRouteRepository
) {

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

    @Transactional
    fun deleteSatelliteData(satelliteId: Long): SatelliteDynamicPlanDeletionSummary {
        val runsBeforeDelete = runRepository.countBySatelliteId(satelliteId)
        val routesBeforeDelete = routeRepository.countBySatelliteId(satelliteId)

        val runsDeleted = runRepository.deleteAllBySatelliteId(satelliteId)
        val orphanRoutesDeleted = routeRepository.deleteAllBySatelliteId(satelliteId)
        val summary = SatelliteDynamicPlanDeletionSummary(
            satelliteId = satelliteId,
            runsDeleted = runsDeleted,
            routesDeletedByRunCascade = routesBeforeDelete - orphanRoutesDeleted,
            orphanRoutesDeleted = orphanRoutesDeleted
        )

        logger.info(
            "Deleted dynamic plan data for satellite: satelliteId={}, runsDeleted={}, runsBeforeDelete={}, routesDeletedByRunCascade={}, orphanRoutesDeleted={}, routesBeforeDelete={}",
            summary.satelliteId,
            summary.runsDeleted,
            runsBeforeDelete,
            summary.routesDeletedByRunCascade,
            summary.orphanRoutesDeleted,
            routesBeforeDelete
        )
        return summary
    }
}

data class SatelliteDynamicPlanDeletionSummary(
    val satelliteId: Long,
    val runsDeleted: Int,
    val routesDeletedByRunCascade: Long,
    val orphanRoutesDeleted: Int
)
