package com.ffii.fpsms.modules.stock.service

import com.ffii.fpsms.modules.stock.entity.projection.StockOutLineInfo
import com.ffii.fpsms.modules.stock.web.model.StockOutLineStatus
import java.math.BigDecimal

/**
 * Workbench / DO scan-pick: which [StockOutLineInfo] rows count as already consuming
 * [pick_order_line] quantity (must stay in sync for scan validation and SPL rebuild).
 *
 * FG legacy may leave SOL as [StockOutLineStatus.CHECKED]; omitting it causes double-pick and SPL sums > POL qty.
 */
object WorkbenchStockOutLinePickProgress {
    fun isCountedAsPicked(info: StockOutLineInfo): Boolean {
        val q = info.qty
        val s = info.status.trim().lowercase()
        // Legacy / mapping gaps: qty posted but status blank — still consumes POL remainder (avoids double pick).
        if (q > BigDecimal.ZERO && s.isEmpty()) return true
        if (s.isEmpty()) return false
        return s == "completed" ||
            s == "partially_completed" ||
            s == "checked" ||
            (s == "rejected" && info.qty > BigDecimal.ZERO) ||
            s.equals(StockOutLineStatus.COMPLETE.status, ignoreCase = true) ||
            s.equals(StockOutLineStatus.PARTIALLY_COMPLETE.status, ignoreCase = true) ||
            s.equals(StockOutLineStatus.CHECKED.status, ignoreCase = true)
    }

    fun sumPickedQty(infos: List<StockOutLineInfo>): BigDecimal =
        infos.filter { isCountedAsPicked(it) }.fold(BigDecimal.ZERO) { acc, i -> acc.add(i.qty) }
}
