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

import com.ffii.core.support.AbstractRepository
import com.ffii.fpsms.modules.purchaseOrder.entity.projections.PurchaseOrderLineInfo
import com.ffii.fpsms.modules.purchaseOrder.enums.PurchaseOrderLineStatus
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import java.io.Serializable

@Repository
interface PurchaseOrderLineRepository : AbstractRepository<PurchaseOrderLine, Long> {
    fun findByM18DataLogIdAndDeletedIsFalse(m18datalogId: Serializable): PurchaseOrderLine?
    fun findAllPurchaseOrderLineInfoByPurchaseOrderIdAndDeletedIsFalse(purchaseOrderId: Long): List<PurchaseOrderLineInfo>
    fun findAllByPurchaseOrderIdAndDeletedIsFalse(purchaseOrderId: Long): List<PurchaseOrderLine>
    fun findAllByPurchaseOrderIdAndDeletedIsFalseAndM18DataLogIsNotNull(purchaseOrderId: Long): List<PurchaseOrderLine>
    fun findAllByPurchaseOrderIdAndStatusNotAndDeletedIsFalse(purchaseOrderId: Long, status: PurchaseOrderLineStatus): List<PurchaseOrderLine>
//    fun findAllByPurchaseOrderIdAndDeletedIsFalse(purchaseOrderId: Long): List<PurchaseOrderLine>
    //    fun find

    /**
     * M18 sync: resolve the local line by PO + M18 line id (m18_data_log.m18Id), not by latest log row id.
     * Newest id first so we attach the new sync to the canonical row when duplicates exist.
     */
    @Query(
        "SELECT pol FROM PurchaseOrderLine pol WHERE pol.deleted = false " +
            "AND pol.purchaseOrder.id = :purchaseOrderId AND pol.m18DataLog.m18Id = :m18LineId ORDER BY pol.id DESC"
    )
    fun findAllByPurchaseOrderIdAndM18LineIdOrderByIdDesc(
        @Param("purchaseOrderId") purchaseOrderId: Long,
        @Param("m18LineId") m18LineId: Long
    ): List<PurchaseOrderLine>

    @Query("SELECT pol FROM PurchaseOrderLine pol WHERE pol.deleted = false AND pol.item IS NOT NULL AND pol.item.isFee = true")
    fun findAllByDeletedIsFalseAndItemIsFeeTrue(): List<PurchaseOrderLine>
}