package com.ffii.fpsms.modules.stock.service

import com.ffii.core.support.AbstractBaseEntityService
import com.ffii.core.support.JdbcDao
import com.ffii.fpsms.modules.master.entity.ItemsRepository
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrder
import com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrderRepository
import com.ffii.fpsms.modules.stock.entity.InventoryLot
import com.ffii.fpsms.modules.stock.entity.InventoryLotRepository
import com.ffii.fpsms.modules.stock.web.model.SaveInventoryRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException

@Service
open class InventoryLotService(
    private val jdbcDao: JdbcDao,
    private val itemsRepository: ItemsRepository,
    private val inventoryLotRepository: InventoryLotRepository,
): AbstractBaseEntityService<InventoryLot, Long, InventoryLotRepository>(jdbcDao, inventoryLotRepository)   {

    @Throws(IOException::class)
    @Transactional
    open fun createOrUpdate(request: SaveInventoryRequest): MessageResponse {
        val inventoryLot = if (request.id !== null) inventoryLotRepository.findById(request.id).orElseThrow() else InventoryLot()
        val thisExpiryDate = if (request.id !== null) inventoryLot.expiryDate else request.expiryDate
        val item = itemsRepository.findById(request.itemId).orElseThrow()
        inventoryLot.apply {
            this.item = item
            stockInDate = request.stockInDate
            expiryDate = thisExpiryDate
            lotNo = request.lotNo
        }
        val savedInventoryLot = saveAndFlush(inventoryLot)
        return MessageResponse(
            id = savedInventoryLot.id,
            code = savedInventoryLot.lotNo,
            name = item.name,
            type = item.type,
            message = "Inventory Lot Save Success",
            errorPosition = null,
            entity = savedInventoryLot,
        )
    }
}