package com.ffii.fpsms.m18.service

import com.ffii.fpsms.m18.entity.M18DataLog
import com.ffii.fpsms.m18.entity.M18DataLogRepository
import com.ffii.fpsms.m18.enums.M18DataLogStatus
import com.ffii.fpsms.m18.model.M18DataLogResponse
import com.ffii.fpsms.m18.model.SaveM18DataLogRequest
import org.springframework.stereotype.Service
import kotlin.jvm.optionals.getOrDefault

@Service
class M18DataLogService(
    val m18DataLogRepository: M18DataLogRepository
) {
    fun findLatestM18DataLogWithSuccess(m18Id: Long, refType: String): M18DataLog? {
        return m18DataLogRepository.findTopByM18IdAndRefTypeAndDeletedIsFalseAndStatusOrderByIdDesc(m18Id, refType, M18DataLogStatus.SUCCESS)
    }

    fun saveM18DataLog(request: SaveM18DataLogRequest): M18DataLogResponse {
        val id = request.id
        val m18DataLog =
            if (id != null && id > 0) m18DataLogRepository.findById(id).getOrDefault(M18DataLog()) else M18DataLog()
        val status = request.statusEnum ?: request.status?.let { status -> M18DataLogStatus.entries.find { it.value == status } }

        m18DataLog.apply {
            refType = request.refType ?: this.refType
            m18Id = request.m18Id ?: this.m18Id
            m18LastModifyDate = request.m18LastModifyDate ?: this.m18LastModifyDate
            dataLog = request.dataLog ?: this.dataLog
            this.status = status
        }

        val response = m18DataLogRepository.saveAndFlush(m18DataLog).let { dataLog ->
            M18DataLogResponse(
                id = dataLog.id,
                refType = dataLog.refType,
                m18Id = dataLog.m18Id,
                status = dataLog.status?.toString(),
            )
        }

        return response
    }
}