package com.ffii.fpsms.modules.master.service

import com.ffii.fpsms.modules.master.entity.Bom
import com.ffii.fpsms.modules.master.entity.BomRepository
import com.ffii.fpsms.modules.master.web.models.SaveBomRequest
import com.ffii.fpsms.modules.master.web.models.SaveBomResponse
import org.springframework.stereotype.Service
import kotlin.jvm.optionals.getOrNull

@Service
open class BomService(
    val bomRepository: BomRepository,
    val itemsService: ItemsService,
    val uomConversionService: UomConversionService
) {

    open fun findAll(): List<Bom> {
        return bomRepository.findAll()
    }

    open fun findById(id: Long): Bom? {
        return bomRepository.findByIdAndDeletedIsFalse(id)
    }

    open fun findByM18Id(m18Id: Long): Bom? {
        return bomRepository.findByM18IdAndDeletedIsFalse(m18Id)
    }

    open fun saveBom(request: SaveBomRequest): SaveBomResponse {

        val item = request.code.let { itemsService.findByM18BomCode(it) } ?: request.itemId?.let { itemsService.findById(it) }

        val uom = request.m18UomId?.let { uomConversionService.findByM18Id(it) }
            ?: request.uomId?.let { uomConversionService.findById(it) }

        val bom = request.m18Id?.let { findByM18Id(it) }
            ?: request.id?.let { findById(it) }
            ?: Bom()

        bom.apply {
            this.item = item
            code = request.code
            name = request.name
            description = request.description
            outputQty = request.outputQty
            outputQtyUom = request.outputQtyUom
            yield = request.yield
            this.uom = uom
            m18Id = request.m18Id ?: m18Id
            m18LastModifyDate = request.m18LastModifyDate ?: m18LastModifyDate
        }

        val response = bomRepository.saveAndFlush(bom).let {
            SaveBomResponse(
                id = it.id,
                code = it.code,
                name = it.name,
                description = it.description,
                outputQty = it.outputQty,
                outputQtyUom = it.outputQtyUom,
                yield = it.yield,
                uomName = uom?.udfudesc,
            )
        }

        return response
    }
}