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

import com.ffii.core.support.AbstractBaseEntityService
import com.ffii.core.support.JdbcDao
import com.ffii.fpsms.modules.master.entity.*
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.master.web.models.NewQcCheckRequest
import com.ffii.fpsms.modules.master.entity.projections.QcCheckInfo
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException

@Service
open class QcCheckService(
    private val jdbcDao: JdbcDao,
    private val itemsRepository: ItemsRepository,
    private val qcCheckRepository: QcCheckRepository,
    private val qcItemRepository: QcItemRepository,
): AbstractBaseEntityService<QcCheck, Long, QcCheckRepository>(jdbcDao, qcCheckRepository) {
    open fun getAllQcCheckInfo(): List<QcCheckInfo> {
        return qcCheckRepository.findAllQcCheckInfoByDeletedFalse()
    }
    open fun getAllQcCheckInfoById(itemId: Long): List<QcCheckInfo> {
        return qcCheckRepository.findAllQcCheckInfoByItemIdAndDeletedFalse(itemId)
    }

    @Throws(IOException::class)
    @Transactional
    open fun saveQcChecks(request: List<NewQcCheckRequest>): MessageResponse {
        if (request.isEmpty()) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = null,
                message = "empty list",
                errorPosition = null,
            )
        }
        val qcChecks = qcCheckRepository.findAllByItemIdAndDeletedFalse(request[0].itemId)
        val qcChecksList = request.map { req ->
            val qc = qcChecks.find { it.qcItem!!.id == req.qcItemId } ?: QcCheck()
            val _qcItem = qcItemRepository.findById(req.qcItemId).orElseThrow()
            qc.apply {
                this.qcItem = _qcItem
                isRange = (req.lowerLimit !== null && req.upperLimit !== null && req.lowerLimit != req.upperLimit)
                description = req.instruction
                systemInput = false
                lowerLimit = req.lowerLimit
                upperLimit = req.upperLimit
                this.item = itemsRepository.findById(req.itemId).orElseThrow()
            }
        }
        val savedQcChecks = qcCheckRepository.saveAllAndFlush(qcChecksList)
        return MessageResponse(
            id = 1,
            name = "total saved: ${savedQcChecks.size}",
            code = null,
            type = null,
            message = "Qc Check Save Success",
            errorPosition = null,
        )
    }

}