package space.nstart.pcp.pcp_satellites_service.repository

import jakarta.transaction.Transactional
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
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_satellites_service.entity.SatelliteModeSnapshotEntity
import java.time.LocalDateTime

interface SatelliteModeSnapshotRepository :
    JpaRepository<SatelliteModeSnapshotEntity, Long>,
    JpaSpecificationExecutor<SatelliteModeSnapshotEntity> {

    fun findAllByComplexPlanRun_IdOrderByIdAsc(runId: Long): List<SatelliteModeSnapshotEntity>

    fun findAllByComplexPlanRun_IdAndSatelliteIdInOrderBySatelliteIdAscCreatedAtDesc(
        runId: Long,
        satelliteIds: Collection<Long>
    ): List<SatelliteModeSnapshotEntity>

    fun findAllBySatelliteIdInAndIsActiveTrueOrderBySatelliteIdAscCreatedAtDesc(
        satelliteIds: Collection<Long>
    ): List<SatelliteModeSnapshotEntity>

    fun findFirstBySatelliteIdAndIsActiveTrueOrderByCreatedAtDescIdDesc(satelliteId: Long): SatelliteModeSnapshotEntity?

    fun countBySatelliteId(satelliteId: Long): Long

    fun deleteAllBySatelliteId(satelliteId: Long): Long

    @Modifying
    @Transactional
    @Query(
        """
        update SatelliteModeSnapshotEntity snapshot
        set snapshot.isActive = false
        where snapshot.satelliteId = :satelliteId
          and snapshot.isActive = true
        """
    )
    fun deactivateActiveSnapshots(@Param("satelliteId") satelliteId: Long): Int

    @Query(
        """
        select snapshot.id
        from SatelliteModeSnapshotEntity snapshot
        where snapshot.satelliteId in :satelliteIds
          and snapshot.intervalStart < :intervalEnd
          and snapshot.intervalEnd > :intervalStart
        """
    )
    fun findIntersectingIdsBySatelliteIdsAndInterval(
        @Param("satelliteIds") satelliteIds: Collection<Long>,
        @Param("intervalStart") intervalStart: LocalDateTime,
        @Param("intervalEnd") intervalEnd: LocalDateTime
    ): List<Long>
}
