package com.ffii.fpsms.modules.stock.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.io.Serializable

@Repository
interface StockTakeRepository : AbstractRepository<StockTake, Long> {
    fun findByIdAndDeletedIsFalse(id: Serializable): StockTake

    fun findAllByStockTakeRoundIdAndDeletedIsFalse(stockTakeRoundId: Long): List<StockTake>

    @Query("""
        select st.code from StockTake st where st.code like :prefix% order by st.code desc limit 1
    """)
    fun findLatestCodeByPrefix(prefix: String): String?

    /** 未刪除列中 stockTakeRoundId 的最大值；全為 null 或無資料時為 0 */
    @Query(
        "SELECT COALESCE(MAX(st.stockTakeRoundId), 0) FROM StockTake st WHERE st.deleted = false"
    )
    fun findMaxStockTakeRoundId(): Long
}