package space.nstart.pcp.complan.db.repository

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 org.springframework.stereotype.Repository
import space.nstart.pcp.complan.db.entity.DynamicPlanRunEntity
import space.nstart.pcp.complan.types.DynamicPlanRunStatus
import java.util.UUID

@Repository
interface DynamicPlanRunRepository : JpaRepository<DynamicPlanRunEntity, UUID> {

    @Query(
        value = """
            select count(*)
            from dynamic_plan_run run
            where exists (
                select 1
                from jsonb_array_elements_text(run.satellite_ids::jsonb) satellite_id(value)
                where satellite_id.value::bigint = :satelliteId
            )
        """,
        nativeQuery = true
    )
    fun countBySatelliteId(@Param("satelliteId") satelliteId: Long): Long

    @Modifying
    @Query(
        value = """
            delete from dynamic_plan_run run
            where exists (
                select 1
                from jsonb_array_elements_text(run.satellite_ids::jsonb) satellite_id(value)
                where satellite_id.value::bigint = :satelliteId
            )
        """,
        nativeQuery = true
    )
    fun deleteAllBySatelliteId(@Param("satelliteId") satelliteId: Long): Int

    @Query(
        value = """
            select *
            from dynamic_plan_run
            order by created_at desc
            limit :limit offset :offset
        """,
        nativeQuery = true
    )
    fun findRuns(
        @Param("limit") limit: Int,
        @Param("offset") offset: Int
    ): List<DynamicPlanRunEntity>

    @Query(
        value = """
            select *
            from dynamic_plan_run
            where status = :status
            order by created_at desc
            limit :limit offset :offset
        """,
        nativeQuery = true
    )
    fun findRunsByStatus(
        @Param("status") status: String,
        @Param("limit") limit: Int,
        @Param("offset") offset: Int
    ): List<DynamicPlanRunEntity>

    fun findAllByStatusIn(statuses: Collection<DynamicPlanRunStatus>): List<DynamicPlanRunEntity>
}
