package com.ffii.fpsms.modules.stock.service

import com.ffii.fpsms.modules.common.SecurityUtils
import com.ffii.fpsms.modules.stock.trace.ItemLotTraceOrchestrator
import com.ffii.fpsms.modules.stock.web.model.ItemLotTraceLocationBlock
import com.ffii.fpsms.modules.stock.web.model.ItemLotTraceResponse
import org.springframework.stereotype.Service

@Service
open class ItemLotTraceService(
    private val orchestrator: ItemLotTraceOrchestrator,
    private val itemLotTraceLogService: ItemLotTraceLogService,
) {
    /** FP-MTMS Version Checklist | Functions Ref. No. 10 | v1.0.0 | 2026-07-17 */
    open fun trace(
        stockInLineId: Long?,
        inventoryLotLineId: Long?,
        lotNo: String?,
        itemId: Long?,
        itemCode: String?,
    ): ItemLotTraceResponse {
        val response = orchestrator.trace(
            stockInLineId,
            inventoryLotLineId,
            lotNo,
            itemId,
            itemCode,
        )
        val lot = response.lot
        itemLotTraceLogService.insertQuietly(
            user = SecurityUtils.getUser().orElse(null),
            inventoryLotId = lot.inventoryLotId,
            lotNo = lot.lotNo,
            itemId = lot.itemId,
            itemCode = lot.itemCode,
        )
        return response
    }

    /**
     * FP-MTMS Version Checklist | Functions Ref. No. 10 | v1.0.0 | 2026-07-17
     * Lazy-load endpoint: returns the full location-scoped trace block for a single inventory lot.
     * Lot-level dimensions (BOM, JO prelude, production, byproducts) are excluded — those are only
     * available via the main /trace endpoint.
     */
    open fun traceLocation(inventoryLotId: Long): ItemLotTraceLocationBlock =
        orchestrator.traceLocation(inventoryLotId)
}
