package space.nstart.pcp.pcp_satellites_service.repository

import org.springframework.data.jpa.repository.EntityGraph
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import space.nstart.pcp.pcp_satellites_service.entity.ComplexPlanRunEntity
import space.nstart.pcp.pcp_satellites_service.entity.ComplexPlanRunStatus
import java.time.LocalDateTime

interface ComplexPlanRunRepository : JpaRepository<ComplexPlanRunEntity, Long>, JpaSpecificationExecutor<ComplexPlanRunEntity> {

    @EntityGraph(attributePaths = ["satellites"])
    @Query("select run from ComplexPlanRunEntity run where run.id = :id")
    fun findDetailedById(@Param("id") id: Long): ComplexPlanRunEntity?

    @EntityGraph(attributePaths = ["satellites"])
    fun findAllByStatusIn(statuses: Collection<ComplexPlanRunStatus>): List<ComplexPlanRunEntity>

    @Query(
        """
        select distinct run.id
        from ComplexPlanRunEntity run
        join run.satellites satellite
        where run.status = :status
          and run.id <> :excludedRunId
          and satellite.satelliteId in :satelliteIds
          and run.intervalStart < :intervalEnd
          and :intervalStart < run.intervalEnd
        order by run.id
        """
    )
    fun findOverlappingRunIdsByStatusAndSatelliteIds(
        @Param("status") status: ComplexPlanRunStatus,
        @Param("satelliteIds") satelliteIds: Collection<Long>,
        @Param("intervalStart") intervalStart: LocalDateTime,
        @Param("intervalEnd") intervalEnd: LocalDateTime,
        @Param("excludedRunId") excludedRunId: Long
    ): List<Long>
}
