package space.nstart.pcp.pcp_request_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_request_service.entity.PDCMEntity
import space.nstart.pcp.pcp_types_lib.dto.ballistics.SatelliteOrbitAvailabilityDTO
import java.time.LocalDateTime

interface PDCMRepository : JpaRepository<PDCMEntity, Long>{

    @Modifying
    @Transactional
    @Query("DELETE FROM  pdcm WHERE satellite_id =:sat", nativeQuery = true)
    fun deleteBySatId(@Param("sat") sat : Long) : Int

    fun findBySatelliteIdAndTimeBetween(id : Long, tBegin : LocalDateTime, tEnd : LocalDateTime) : List<PDCMEntity>

    @Query(
        """
        select new space.nstart.pcp.pcp_types_lib.dto.ballistics.SatelliteOrbitAvailabilityDTO(
            p.satelliteId,
            min(p.time),
            max(p.time)
        )
        from PDCMEntity p
        group by p.satelliteId
        order by p.satelliteId
        """
    )
    fun findSatelliteOrbitAvailability(): List<SatelliteOrbitAvailabilityDTO>

    @Query(
        """
        select new space.nstart.pcp.pcp_types_lib.dto.ballistics.SatelliteOrbitAvailabilityDTO(
            p.satelliteId,
            min(p.time),
            max(p.time)
        )
        from PDCMEntity p
        group by p.satelliteId
        having :time between min(p.time) and max(p.time)
        order by p.satelliteId
        """
    )
    fun findSatelliteOrbitAvailabilityAtTime(@Param("time") time: LocalDateTime): List<SatelliteOrbitAvailabilityDTO>

    @Query(
        """
        select new space.nstart.pcp.pcp_types_lib.dto.ballistics.SatelliteOrbitAvailabilityDTO(
            p.satelliteId,
            min(p.time),
            max(p.time)
        )
        from PDCMEntity p
        where p.time >= :dayStart and p.time < :dayEnd
        group by p.satelliteId
        order by p.satelliteId
        """
    )
    fun findSatelliteOrbitAvailabilityForDate(
        @Param("dayStart") dayStart: LocalDateTime,
        @Param("dayEnd") dayEnd: LocalDateTime
    ): List<SatelliteOrbitAvailabilityDTO>
}
