package com.ffii.fpsms.modules.master.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import java.util.Optional

interface BomDurationAggregate {
    val bomId: Long
    val totalMinutes: Long
}

@Repository
interface BomProcessRepository : AbstractRepository<BomProcess, Long> {
    fun findBySeqNoAndBomIdAndDeletedIsFalse(seqNo: Int, bomId: Long): BomProcess?
    fun findByBomIdOrderBySeqNo(bomId: Long): List<BomProcess>
    fun findByBomId(bomId: Long): List<BomProcess>
    fun findAllByBomIdAndDeletedFalse(bomId: Long): List<BomProcess>

    @Query(
        """
        SELECT 
            bp.bom.id AS bomId,
            COALESCE(SUM(COALESCE(bp.durationInMinute, 0)), 0) AS totalMinutes
        FROM BomProcess bp
        WHERE bp.deleted = false
          AND bp.bom.id IN :bomIds
        GROUP BY bp.bom.id
        """
    )
    fun sumDurationByBomIds(@Param("bomIds") bomIds: Collection<Long>): List<BomDurationAggregate>
}