package space.nstart.pcp.pcp_request_service.service

import org.springframework.stereotype.Service
import space.nstart.pcp.pcp_request_service.utils.UtcDateTimes
import java.time.Clock
import org.springframework.transaction.annotation.Transactional
import space.nstart.pcp.pcp_request_service.entity.SatelliteInitialConditionEntity
import space.nstart.pcp.pcp_request_service.repository.SatelliteInitialConditionRepository
import space.nstart.pcp.pcp_types_lib.dto.ballistics.SatelliteICDTO

@Service
class SatelliteInitialConditionService(
    private val satelliteInitialConditionRepository: SatelliteInitialConditionRepository,
    private val clock: Clock
) {

    @Transactional
    fun saveReceived(request: SatelliteICDTO): SatelliteInitialConditionEntity =
        satelliteInitialConditionRepository.save(SatelliteInitialConditionEntity(request, UtcDateTimes.now(clock)))

    @Transactional
    fun markLastCalculated(initialCondition: SatelliteInitialConditionEntity) {
        satelliteInitialConditionRepository.clearLastCalculated(initialCondition.satelliteId)
        initialCondition.markLastCalculated(UtcDateTimes.now(clock))
        satelliteInitialConditionRepository.save(initialCondition)
    }

    @Transactional(readOnly = true)
    fun current(satelliteId: Long): SatelliteICDTO? =
        satelliteInitialConditionRepository
            .findFirstBySatelliteIdAndLastCalculatedTrueOrderByCalculatedAtDescIdDesc(satelliteId)
            ?.toDto()
}
