package com.ffii.fpsms.m18.service

import com.ffii.fpsms.m18.entity.M18Cunit
import com.ffii.fpsms.m18.entity.M18CunitRepository
import com.ffii.fpsms.m18.model.M18UnitData
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.math.BigDecimal

/**
 * Persists M18 `cunit` lines from GET /root/api/read/unit.
 * DB [M18Cunit.ratioN] ← JSON `ratioD`, DB [M18Cunit.ratioD] ← JSON `ratioN`.
 */
@Service
open class M18CunitService(
    private val m18CunitRepository: M18CunitRepository,
) {
    data class UnitRatios(
        val ratioN: BigDecimal?,
        val ratioD: BigDecimal?,
    )

    @Transactional
    open fun replaceForUnit(m18Id: Long, data: M18UnitData) {
        m18CunitRepository.deleteByM18Id(m18Id)
        data.cunit.orEmpty().forEach { c ->
            val row = M18Cunit().apply {
                this.m18Id = m18Id
                m18CunitLineId = c.id
                ratioN = c.ratioD
                ratioD = c.ratioN
                hId = c.hId
                unitId = c.unitId
                iRev = c.iRev
                itemNo = c.itemNo?.trim()?.ifBlank { null }
            }
            m18CunitRepository.save(row)
        }
    }

    open fun countActiveRows(): Long {
        return m18CunitRepository.countByDeletedFalse()
    }

    /**
     * Resolve unit conversion ratio by M18 unit id from m18_cunit.
     * Prefer exact row m18Id+unitId; fallback to first row under m18Id.
     */
    open fun resolveRatiosByM18UnitId(unitM18Id: Long): UnitRatios? {
        val exact = m18CunitRepository.findFirstByM18IdAndUnitIdAndDeletedFalse(unitM18Id, unitM18Id)
        if (exact != null) {
            return UnitRatios(ratioN = exact.ratioN, ratioD = exact.ratioD)
        }
        val fallback = m18CunitRepository.findFirstByM18IdAndDeletedFalseOrderByIdAsc(unitM18Id)
        return fallback?.let { UnitRatios(ratioN = it.ratioN, ratioD = it.ratioD) }
    }
}
