package space.nstart.pcp.pcp_mission_planing_service.repository

import jakarta.transaction.Transactional
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import space.nstart.pcp.pcp_mission_planing_service.entity.ModeEntity
import java.time.LocalDateTime
import java.util.UUID

interface ModeRepository : JpaRepository<ModeEntity, Long> {
    fun findAllByPlan_IdOrderByTimeStartAsc(planId: Long): List<ModeEntity>
    fun findAllByPlan_Mission_MissionIdOrderByTimeStartAsc(missionId: UUID): List<ModeEntity>
    fun findAllByPlan_Mission_SatelliteIdAndTimeStartIsNotNullAndTimeStartLessThanEqualOrderByTimeStartAsc(
        satelliteId: Long,
        timeStop: LocalDateTime
    ): List<ModeEntity>

    fun countByPlan_Mission_SatelliteId(satelliteId: Long): Long

    @Modifying
    @Transactional
    @Query("DELETE FROM modes WHERE plan_id = :planId AND type = 'SURVEY'", nativeQuery = true)
    fun deleteSurveyModesByPlanId(@Param("planId") planId: Long): Int

    /**
     * Удаляет только пересчитываемые маршруты съёмки плана, сохраняя ручные
     * (source = 'MANUAL'). Используется при пересчёте плана (этап 5, loadSlots),
     * чтобы не затирать добавленные оператором съёмки.
     */
    @Modifying
    @Transactional
    @Query(
        "DELETE FROM modes WHERE plan_id = :planId AND type = 'SURVEY' " +
            "AND id NOT IN (SELECT id FROM survey_modes WHERE source = 'MANUAL')",
        nativeQuery = true
    )
    fun deleteRecalculableSurveyModesByPlanId(@Param("planId") planId: Long): Int

    @Modifying
    @Transactional
    @Query("DELETE FROM modes WHERE plan_id = :planId AND type = 'DROP'", nativeQuery = true)
    fun deleteDropModesByPlanId(@Param("planId") planId: Long): Int
}
