package com.ffii.fpsms.modules.master.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 BomMaterialRepository : AbstractRepository<BomMaterial, Long> {
    fun findByIdAndDeletedIsFalse(id: Serializable): BomMaterial?

    fun findByM18IdAndDeletedIsFalse(m18Id: Long): BomMaterial?

    fun findAllByBomItemIdAndDeletedIsFalse(itemId: Long): List<BomMaterial>

    fun findAllByBomIdAndDeletedIsFalse(bomId: Long): List<BomMaterial>

    fun findByBomIdAndItemId(bomId: Long, itemId: Long): BomMaterial?

    /** Single round-trip for master-data scans (avoids per-bom N+1). */
    @Query(
        """
        SELECT bm FROM BomMaterial bm
        JOIN FETCH bm.bom b
        LEFT JOIN FETCH bm.item
        LEFT JOIN FETCH bm.uom
        LEFT JOIN FETCH bm.salesUnit
        WHERE bm.deleted = false AND b.deleted = false
        """,
    )
    fun findAllActiveForActiveBoms(): List<BomMaterial>
}