package com.ffii.fpsms.modules.purchaseQuotation.service

import com.ffii.fpsms.modules.master.service.ItemUomService
import com.ffii.fpsms.modules.master.service.ItemsService
import com.ffii.fpsms.modules.master.service.UomConversionService
import com.ffii.fpsms.modules.purchaseQuotation.entity.PurchaseQuotationLine
import com.ffii.fpsms.modules.purchaseQuotation.entity.PurchaseQuotationLineRepository
import com.ffii.fpsms.modules.purchaseQuotation.web.model.SavePurchaseQuotationLineRequest
import com.ffii.fpsms.modules.purchaseQuotation.web.model.SavePurchaseQuotationLineResponse
import org.springframework.stereotype.Service

@Service
open class PurchaseQuotationLineService (
    private val purchaseQuotationLineRepository: PurchaseQuotationLineRepository,
    private val purchaseQuotationService: PurchaseQuotationService,
    private val itemsService: ItemsService,
    private val uomConversionService: UomConversionService,
    private val itemUomService: ItemUomService,
) {
    open fun findById(id: Long): PurchaseQuotationLine? {
        return purchaseQuotationLineRepository.findByIdAndDeletedIsFalse(id);
    }

    open fun findByM18Id(m18Id: Long): PurchaseQuotationLine? {
        return purchaseQuotationLineRepository.findByM18IdAndDeletedIsFalse(m18Id);
    }

    open fun savePurchaseQuotationLine(request: SavePurchaseQuotationLineRequest): SavePurchaseQuotationLineResponse {
        val purchaseQuotationLine = request.m18Id?.let { findByM18Id(it) } ?: request.id?.let { findById(it) } ?: PurchaseQuotationLine()
        val purchaseQuotation = request.purchaseQuotationId?.let { purchaseQuotationService.findById(it) }
        val item = request.m18ItemId?.let { itemsService.findByM18Id(it) } ?: request.itemId?.let { itemsService.findById(it) }
        val uom = request.uomId?.let { uomConversionService.findById(it) } ?: item?.id?.let { itemUomService.findPurchaseUnitByM18ItemId(it)?.uom }

        purchaseQuotationLine.apply {
            this.purchaseQuotation = purchaseQuotation
            this.item = item
            code = request.code
            description = request.description
            this.uom = uom
            m18Id = request.m18Id ?: this.m18Id
            m18LastModifyDate = request.m18LastModifyDate ?: this.m18LastModifyDate
        }

        val response = purchaseQuotationLineRepository.saveAndFlush(purchaseQuotationLine).let {
            SavePurchaseQuotationLineResponse(
                id = it.id,
                itemCode = it.item?.code,
                code = it.code,
                description = it.description,
                uomCode = it.uom?.code
            )
        }

        return response
    }
}