package com.ffii.fpsms.m18.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import java.time.LocalDateTime

interface M18GoodsReceiptNoteLogRepository : AbstractRepository<M18GoodsReceiptNoteLog, Long> {

    /** Returns true if a successful GRN was already created for this PO (legacy / broad check). */
    fun existsByPurchaseOrderIdAndStatusTrue(purchaseOrderId: Long): Boolean

    /** True if this stock-in line was already included in a successful M18 GRN (one delivery = one GRN batch). */
    fun existsByStockInLineIdAndStatusTrue(stockInLineId: Long): Boolean

    /**
     * GRN log rows that need M18 AN code backfill: have record id, no grn_code yet,
     * created in [start, end] inclusive (e.g. start = 4 days ago 00:00, end = now).
     */
    @Query(
        """
        SELECT l FROM M18GoodsReceiptNoteLog l
        WHERE l.deleted = false
          AND l.m18RecordId IS NOT NULL
          AND (l.grnCode IS NULL OR l.grnCode = '')
          AND l.created >= :start AND l.created <= :end
        """
    )
    fun findNeedingGrnCode(
        @Param("start") start: LocalDateTime,
        @Param("end") end: LocalDateTime,
    ): List<M18GoodsReceiptNoteLog>
}
