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

import com.ffii.fpsms.modules.master.service.ShopService
import com.ffii.fpsms.modules.purchaseQuotation.entity.PurchaseQuotation
import com.ffii.fpsms.modules.purchaseQuotation.entity.PurchaseQuotationRepository
import com.ffii.fpsms.modules.purchaseQuotation.web.model.SavePurchaseQuotationRequest
import com.ffii.fpsms.modules.purchaseQuotation.web.model.SavePurchaseQuotationResponse
import org.springframework.stereotype.Service

@Service
open class PurchaseQuotationService(
    private val purchaseQuotationRepository: PurchaseQuotationRepository,
    private val shopService: ShopService,
) {
    open fun findById(id: Long): PurchaseQuotation? {
        return purchaseQuotationRepository.findByIdAndDeletedIsFalse(id);
    }

    open fun findByM18Id(m18Id: Long): PurchaseQuotation? {
        return purchaseQuotationRepository.findByM18IdAndDeletedIsFalse(m18Id);
    }

    open fun savePurchaseQuotation(request: SavePurchaseQuotationRequest): SavePurchaseQuotationResponse {
        val purchaseQuotation = request.m18Id?.let { findByM18Id(it) } ?: request.id?.let { findById(it) } ?: PurchaseQuotation()
        val shop = request.m18ShopId?.let { shopService.findVendorByM18Id(it) } ?: request.shopId?.let { shopService.findById(it) }
        val currency = request.m18CurrencyId?.let {  }

        purchaseQuotation.apply {
            code = request.code
            expiryDate = request.expiryDate
            effectiveDate = request.effectiveDate
            this.shop = shop
            remarks = request.remarks
            m18Id = request.m18Id
            m18LastModifyDate = request.m18LastModifyDate
        }

        val response = purchaseQuotationRepository.saveAndFlush(purchaseQuotation).let {
            SavePurchaseQuotationResponse(
                id = it.id,
                code = it.code,
                expiryDate = it.expiryDate,
                effectiveDate = it.effectiveDate,
                shopCode = it.shop?.code,
                remarks = it.remarks
            )
        }

        return response
    }
}