package com.ffii.fpsms.modules.common.alert

/**
 * Parses PO line sync failure rows written by [com.ffii.fpsms.m18.service.M18PurchaseOrderService].
 * Expected format: "PO {code} Cannot resolve local item for M18 proId={id}".
 */
internal object PoLineFailureAlertSupport {
    private val WITH_PO_CODE =
        Regex("^PO (\\S+) Cannot resolve local item for M18 proId=(\\d+)$")

    /** @return (poCode, bullet line for email) or null when the message cannot be parsed. */
    fun parseExceptionMessage(raw: String?): Pair<String, String>? {
        val trimmed = raw?.trim().orEmpty()
        if (trimmed.isEmpty()) {
            return null
        }
        val match = WITH_PO_CODE.matchEntire(trimmed) ?: return null
        val poCode = match.groupValues[1]
        val proId = match.groupValues[2]
        return poCode to "Cannot resolve local item for M18 proId=$proId"
    }

    fun buildEmailBody(poCode: String, bulletLines: Collection<String>): String {
        val detail = bulletLines.joinToString("\n") { "- $it" }
        return "FPSMS PO_LINE FAIL: $poCode\n\n$detail"
    }
}
