package space.nstart.pcp.routepassportconsumer.repository

import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import space.nstart.pcp.routepassportconsumer.entity.RoutePassportOutboxEntity
import java.util.UUID

interface RoutePassportOutboxRepository : JpaRepository<RoutePassportOutboxEntity, UUID> {
    fun existsByRouteIdAndEventType(routeId: UUID, eventType: String): Boolean

    @Query(
        value = """
            SELECT *
            FROM route_passport_outbox
            WHERE status = 'PENDING'
              AND next_attempt_at <= now()
              AND (locked_until IS NULL OR locked_until < now())
            ORDER BY created_at
            LIMIT :limit
            FOR UPDATE SKIP LOCKED
        """,
        nativeQuery = true,
    )
    fun findDueForUpdateSkipLocked(@Param("limit") limit: Int): List<RoutePassportOutboxEntity>
}
