package com.ffii.fpsms.modules.qc.entity

import com.ffii.core.support.AbstractRepository
import com.ffii.fpsms.modules.qc.entity.projection.QcResultInfo
import com.ffii.fpsms.modules.stock.entity.StockInLine
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository

@Repository
interface QcResultRepository: AbstractRepository<QcResult, Long> {
    fun findQcResultInfoByStockInLineIdAndDeletedFalse(stockInLineId: Long): List<QcResultInfo>
    fun findQcResultInfoByStockOutLineIdAndDeletedFalse(stockOutLineId: Long): List<QcResultInfo>

    @Query(
        """
        SELECT DISTINCT qr.stockInLine.id
        FROM QcResult qr
        WHERE qr.deleted = false
          AND qr.stockInLine.id IN :stockInLineIds
        """
    )
    fun findDistinctStockInLineIdsByStockInLineIdInAndDeletedFalse(
        @Param("stockInLineIds") stockInLineIds: List<Long>
    ): List<Long>

    @Query(
        """
        SELECT DISTINCT qr.stockInLine.id
        FROM QcResult qr
        WHERE qr.deleted = false
          AND qr.stockInLine.id IN :stockInLineIds
          AND (qr.qcPassed = false OR COALESCE(qr.failQty, 0) > 0)
        """
    )
    fun findDistinctFailedStockInLineIdsByStockInLineIdInAndDeletedFalse(
        @Param("stockInLineIds") stockInLineIds: List<Long>
    ): List<Long>
}