package space.nstart.pcp_tgu_service.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 space.nstart.pcp_tgu_service.entity.VisibilityRefreshJobEntity
import java.time.LocalDateTime

/** Доступ к refresh jobs окон видимости. */
interface VisibilityRefreshJobRepository : JpaRepository<VisibilityRefreshJobEntity, String> {
    /** Атомарно ставит или переоткрывает coalesced refresh job по spacecraftId. */
    @Modifying
    @Query(
        value = """
            INSERT INTO visibility_refresh_job(
                spacecraft_id,
                norad_id,
                status,
                reason,
                locked_by,
                locked_until,
                rerun_requested,
                requested_at,
                updated_at
            )
            VALUES (
                :spacecraftId,
                :noradId,
                'PENDING',
                :reason,
                NULL,
                NULL,
                FALSE,
                :now,
                :now
            )
            ON CONFLICT (spacecraft_id) DO UPDATE SET
                norad_id = COALESCE(EXCLUDED.norad_id, visibility_refresh_job.norad_id),
                status = CASE
                    WHEN visibility_refresh_job.status = 'RUNNING' THEN visibility_refresh_job.status
                    ELSE 'PENDING'
                END,
                reason = EXCLUDED.reason,
                locked_by = CASE
                    WHEN visibility_refresh_job.status = 'RUNNING' THEN visibility_refresh_job.locked_by
                    ELSE NULL
                END,
                locked_until = CASE
                    WHEN visibility_refresh_job.status = 'RUNNING' THEN visibility_refresh_job.locked_until
                    ELSE NULL
                END,
                rerun_requested = CASE
                    WHEN visibility_refresh_job.status = 'RUNNING' THEN TRUE
                    ELSE FALSE
                END,
                requested_at = EXCLUDED.requested_at,
                updated_at = EXCLUDED.updated_at
        """,
        nativeQuery = true
    )
    fun upsertPending(
        @Param("spacecraftId") spacecraftId: String,
        @Param("noradId") noradId: Long?,
        @Param("reason") reason: String,
        @Param("now") now: LocalDateTime
    ): Int

    /** Claim pending или просроченные running jobs через row locks для горизонтального scale-out. */
    @Query(
        value = """
            SELECT *
            FROM visibility_refresh_job
            WHERE status = 'PENDING'
               OR (
                    status = 'RUNNING'
                    AND locked_until < :now
               )
            ORDER BY requested_at
            LIMIT :limit
            FOR UPDATE SKIP LOCKED
        """,
        nativeQuery = true
    )
    fun findPendingForUpdate(
        @Param("now") now: LocalDateTime,
        @Param("limit") limit: Int
    ): List<VisibilityRefreshJobEntity>
}
