package com.ffii.fpsms.modules.pickOrder.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.stereotype.Repository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
@Repository
interface PickOrderLineRepository : AbstractRepository<PickOrderLine, Long> {
    @Query("""
    SELECT DISTINCT pol.pickOrder 
    FROM PickOrderLine pol 
    WHERE pol.item.id = :itemId 
    AND pol.pickOrder.status IN ('PENDING', 'PARTIALLY_COMPLETED', 'RELEASED')
    AND pol.pickOrder.deleted = false
""")
fun findAllPickOrdersByItemId(@Param("itemId") itemId: Long): List<PickOrder>


@Query("""
    SELECT pol FROM PickOrderLine pol 
    WHERE pol.pickOrder.id = :pickOrderId AND pol.deleted = false
""")
fun findAllByPickOrderId(@Param("pickOrderId") pickOrderId: Long): List<PickOrderLine>
fun findAllByPickOrderIdAndDeletedFalse(pickOrderId: Long): List<PickOrderLine>
fun findByPickOrderId(pickOrderId: Long): List<PickOrderLine>

@Query(
    """
    SELECT pol FROM PickOrderLine pol
    WHERE pol.pickOrder.id IN :pickOrderIds AND pol.deleted = false
    """
)
fun findAllByPickOrderIdInAndDeletedFalse(@Param("pickOrderIds") pickOrderIds: List<Long>): List<PickOrderLine>

@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(
    value = """
        UPDATE fpsmsdb.pick_order_line
        SET status = 'completed',
            modified = CURRENT_TIMESTAMP
        WHERE id = :pickOrderLineId
          AND deleted = 0
          AND LOWER(COALESCE(status, '')) <> 'completed'
    """,
    nativeQuery = true,
)
fun markCompletedIfNotCompleted(@Param("pickOrderLineId") pickOrderLineId: Long): Int
}