package com.ffii.fpsms.modules.purchaseOrder.entity

import com.ffii.core.support.AbstractRepository
import com.ffii.fpsms.modules.purchaseOrder.entity.projections.PurchaseOrderDataClass
import com.ffii.fpsms.modules.purchaseOrder.entity.projections.PurchaseOrderInfo
import org.springframework.data.domain.Page
import org.springframework.stereotype.Repository
import java.io.Serializable
import java.time.LocalDateTime
import java.util.Optional
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param

@Repository
interface PurchaseOrderRepository : AbstractRepository<PurchaseOrder, Long> {
    fun findTopByM18DataLogIdAndDeletedIsFalseOrderByModifiedDesc(m18datalogId: Serializable): PurchaseOrder?

    fun findPurchaseOrderInfoByIdAndDeletedIsFalse(id: Long): PurchaseOrderInfo

    fun findByIdAndDeletedFalse(id: Long): Optional<PurchaseOrder>

    @Query(
        """
        SELECT po FROM PurchaseOrder po
        WHERE po.deleted = false
          AND po.estimatedArrivalDate IS NOT NULL
          AND po.estimatedArrivalDate >= :from
          AND po.estimatedArrivalDate < :to
        """
    )
    fun findAllByEstimatedArrivalDateRange(
        @Param("from") from: LocalDateTime,
        @Param("to") to: LocalDateTime
    ): List<PurchaseOrder>

    override fun findAll(pageable: Pageable): Page<PurchaseOrder>
}