package space.nstart.pcp_tgu_service.service

import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import space.nstart.pcp_tgu_service.entity.PlannedPlanEntity
import space.nstart.pcp_tgu_service.repository.PlannedPlanRepository
import java.time.LocalDateTime
import java.util.UUID

/**
 * Read-only query service для persisted planned_plan.
 */
@Service
class PlanQueryService(
    private val plannedPlanRepository: PlannedPlanRepository
) {
    /** Возвращает все persisted планы с отсечением глубокой истории. */
    @Transactional(readOnly = true)
    fun getAllPlans(historyDays: Long): List<PlannedPlanEntity> {
        val historySince = LocalDateTime.now().minusDays(historyDays.coerceAtLeast(0))
        return plannedPlanRepository.findAllByOrderByStartTime()
            .filter { plan -> plan.endTime >= historySince }
    }

    /** Возвращает persisted планы одного КА с отсечением глубокой истории. */
    @Transactional(readOnly = true)
    fun getPlansBySpacecraftId(spacecraftId: String, historyDays: Long): List<PlannedPlanEntity> {
        val historySince = LocalDateTime.now().minusDays(historyDays.coerceAtLeast(0))
        return plannedPlanRepository.findAllBySpacecraftIdOrderByStartTime(spacecraftId)
            .filter { plan -> plan.endTime >= historySince }
    }

    /** Возвращает persisted plan по ID для test-only/debug API. */
    @Transactional(readOnly = true)
    fun getByPlanId(planId: UUID): PlannedPlanEntity =
        plannedPlanRepository.findById(planId)
            .orElseThrow { ResponseStatusException(HttpStatus.NOT_FOUND, "Plan with planId=$planId was not found") }
}
