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

import com.ffii.fpsms.modules.master.entity.Currency
import com.ffii.fpsms.modules.master.entity.CurrencyRepository
import com.ffii.fpsms.modules.master.web.models.SaveCurrencyRequest
import org.springframework.stereotype.Service

@Service
open class CurrencyService(
    val currencyRepository: CurrencyRepository,
) {
    open fun findById(id: Long): Currency? {
        return currencyRepository.findByIdAndDeletedIsFalse(id);
    }

    open fun findByM18Id(m18Id: Long): Currency? {
        return currencyRepository.findByM18IdAndDeletedIsFalse(m18Id);
    }

    open fun saveCurrency(request: SaveCurrencyRequest): Currency {
        val currency = request.m18Id?.let { findByM18Id(it) } ?: request.id?.let { findById(it) } ?: Currency()

        currency.apply {
            code = request.code
            name = request.name
            description = request.description
            m18Id = request.m18Id
            m18LastModifyDate = request.m18LastModifyDate
        }

        return currencyRepository.saveAndFlush(currency)
    }
}