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

import com.ffii.fpsms.modules.jobOrder.web.model.CreateJobOrderBomMaterialRequest
import com.ffii.fpsms.modules.master.entity.*
import com.ffii.fpsms.modules.master.web.models.SaveBomMaterialRequest
import com.ffii.fpsms.modules.master.web.models.SaveBomMaterialResponse
import org.springframework.stereotype.Service

@Service
open class BomMaterialService(
    val bomMaterialRepository: BomMaterialRepository,
    val itemsService: ItemsService,
    val uomConversionService: UomConversionService,
    val bomService: BomService,
) {
    open fun findById(id: Long): BomMaterial? {
        return bomMaterialRepository.findByIdAndDeletedIsFalse(id);
    }

    open fun findByM18Id(m18Id: Long): BomMaterial? {
        return bomMaterialRepository.findByM18IdAndDeletedIsFalse(m18Id);
    }

    open fun findAllByBomId(bomId: Long): List<BomMaterial> {
        return bomMaterialRepository.findAllByBomIdAndDeletedIsFalse(bomId);
    }

    open fun saveBomMaterial(request: SaveBomMaterialRequest): SaveBomMaterialResponse {
        val bomMaterial = request.m18Id?.let { findByM18Id(it) }
            ?: request.id?.let { findById(it) }
            ?: BomMaterial();

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

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

        val bom = request.m18BomId?.let { bomService.findById(it) }
            ?: request.bomId?.let { bomService.findById(it) }
            ?: Bom()

        bomMaterial.apply {
            this.item = item
            itemName = request.itemName
            isConsumable = request.isConsumable
            qty = request.qty
            this.uom = uom
            uomName = request.uomName
            this.bom = bom
            m18Id = request.m18Id ?: m18Id
            m18LastModifyDate = request.m18LastModifyDate ?: m18LastModifyDate
            remarks = request.remarks
        }

        val response = bomMaterialRepository.saveAndFlush(bomMaterial).let {
            SaveBomMaterialResponse(
                id = it.id,
                itemName = it.itemName,
                isConsumable = it.isConsumable,
                qty = it.qty,
                uomName = it.uomName,
                bomCode = it.bom?.code,
                remarks = it.remarks
            )
        }

        return response
    }
}