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.web.models.MessageResponse
import com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrderRepository
import com.ffii.fpsms.modules.stock.entity.StockIn
import com.ffii.fpsms.modules.stock.entity.StockInLine
import com.ffii.fpsms.modules.stock.entity.StockInLineRepository
import com.ffii.fpsms.modules.stock.entity.StockInRepository
import com.ffii.fpsms.modules.stock.web.model.SaveStockInRequest
import com.ffii.fpsms.modules.stock.web.model.StockInStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException

@Service
open class StockInService(
    private val jdbcDao: JdbcDao,
    private val stockInRepository: StockInRepository,
    private val purchaseOrderRepository: PurchaseOrderRepository,
    ): AbstractBaseEntityService<StockIn, Long, StockInRepository>(jdbcDao, stockInRepository) {

    @Throws(IOException::class)
    @Transactional
    open fun create(request: SaveStockInRequest): MessageResponse {
        val stockIn = StockIn()
        val purchaseOrder = if (request.purchaseOrderId != null)
            purchaseOrderRepository.findByIdAndDeletedFalse(request.purchaseOrderId).orElseThrow()
            else return MessageResponse(
            id = null,
            code = null,
            name = null,
            type = "Found Null",
            message = "request.purchaseOrderId is null",
            errorPosition = "Stock In"
        )
        stockIn.apply {
            code = purchaseOrder.code
            supplier = purchaseOrder.supplier
            this.purchaseOrder = purchaseOrder
//            shop = purchaseOrder.shop
            orderDate = purchaseOrder.orderDate
            estimatedCompleteDate = purchaseOrder.estimatedArrivalDate?.toLocalDate()
            completeDate = purchaseOrder.completeDate
            status = StockInStatus.PENDING.status
        }
        val savedStockIn = saveAndFlush(stockIn)
        return MessageResponse(
            id = savedStockIn.id,
            code = savedStockIn.code,
            name = savedStockIn.code,
            type = "stock in created: status = ${savedStockIn.status}",
            message = "save success",
            errorPosition = null,
            entity = savedStockIn
        )
    }
}