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

import com.ffii.fpsms.modules.master.entity.UomConversionRepository
import com.ffii.fpsms.modules.stock.entity.InventoryLotLineRepository
import com.ffii.fpsms.modules.stock.entity.StockTakeLine
import com.ffii.fpsms.modules.stock.entity.StockTakeLineRepository
import com.ffii.fpsms.modules.stock.entity.StockTakeRepository
import com.ffii.fpsms.modules.stock.enums.StockTakeLineStatus
import com.ffii.fpsms.modules.stock.web.model.SaveStockTakeLineRequest
import org.springframework.stereotype.Service

@Service
open class StockTakeLineService(
    val stockTakeLineRepository: StockTakeLineRepository,
    val stockTakeRepository: StockTakeRepository,
    val inventoryLotLineRepository: InventoryLotLineRepository,
    val uomConversionRepository: UomConversionRepository,
    val inventoryLotLineService: InventoryLotLineService,
) {
    fun saveStockTakeLine(request: SaveStockTakeLineRequest): StockTakeLine {
        val stockTake = request.stockTakeId?.let { stockTakeRepository.findByIdAndDeletedIsFalse(it) } ?: throw Exception("Cant Find Stock Take");
        val inventoryLotLine = request.inventoryLotLineId?.let { inventoryLotLineRepository.findByIdAndDeletedIsFalse(it) };
        val uom = request.uomId?.let { uomConversionRepository.findByIdAndDeletedFalse(it) };
        val status = request.status?.let { _status -> StockTakeLineStatus.entries.find { it.value == _status} }

        val stockTakeLine = request.id?.let { stockTakeLineRepository.findByIdAndDeletedIsFalse(it) } ?: StockTakeLine();

        // will skip null
        stockTake.let { stockTakeLine.stockTake = it }
        inventoryLotLine.let { stockTakeLine.inventoryLotLine = it }
        uom.let { stockTakeLine.uom = it }
        request.initialQty?.let { stockTakeLine.initialQty = it }
        request.finalQty?.let { stockTakeLine.finalQty = it }
        request.completeDate?.let { stockTakeLine.completeDate = it }
        status?.let { stockTakeLine.status = it }
        request.remarks?.let { stockTakeLine.remarks = it }

        return stockTakeLineRepository.save(stockTakeLine);
    }
}