package com.ffii.fpsms.py



import com.ffii.fpsms.modules.jobOrder.entity.JobOrder

import com.ffii.fpsms.modules.master.service.ItemUomService

import com.ffii.fpsms.modules.stock.entity.StockInLineRepository



object PyJobOrderListMapper {

    fun toListItem(

        jo: JobOrder,

        printed: PrintedQtyByChannel?,

        stockInLineRepository: StockInLineRepository,

        itemUomService: ItemUomService,

    ): PyJobOrderListItem {

        val itemCode = jo.bom?.item?.code ?: jo.bom?.code

        val baseName = jo.bom?.name ?: jo.bom?.item?.name

        val itemId = jo.bom?.item?.id

        val stockUnitDesc = itemId?.let { id ->

            itemUomService.findStockUnitByItemId(id)?.uom?.udfudesc

        }?.trim().orEmpty()

        val baseTrim = baseName?.trim().orEmpty()

        val baseAlreadyHasParens = '(' in baseTrim && ')' in baseTrim

        val itemName = when {

            stockUnitDesc.isEmpty() && baseTrim.isEmpty() -> null

            stockUnitDesc.isEmpty() -> baseTrim

            baseTrim.isEmpty() -> "($stockUnitDesc)"

            baseAlreadyHasParens -> baseTrim

            else -> "$baseTrim($stockUnitDesc)"

        }

        val stockInLine = jo.id?.let { stockInLineRepository.findFirstByJobOrder_IdAndDeletedFalse(it) }

        val stockInLineId = stockInLine?.id

        val lotNo = stockInLine?.lotNo

        val p = printed ?: PrintedQtyByChannel()

        return PyJobOrderListItem(

            id = jo.id!!,

            code = jo.code,

            planStart = jo.planStart,

            itemCode = itemCode,

            itemName = itemName,

            reqQty = jo.reqQty,

            stockInLineId = stockInLineId,

            itemId = itemId,

            lotNo = lotNo,

            bagPrintedQty = p.bagPrintedQty,

            labelPrintedQty = p.labelPrintedQty,

            laserPrintedQty = p.laserPrintedQty,

        )

    }

}

