package com.ffii.fpsms.m18.service

import com.ffii.fpsms.api.service.ApiCallerService
import com.ffii.fpsms.m18.model.M18BomListResponse
import com.ffii.fpsms.m18.model.M18CommonListRequest
import com.ffii.fpsms.m18.model.StSearchType
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

/**
 * M18 udfBomForShop header lookup by [code] — isolated from [M18MasterDataService] / [M18BomForShopService] cycles.
 */
@Service
open class M18BomHeaderLookupService(
    private val apiCallerService: ApiCallerService,
) {
    private val logger: Logger = LoggerFactory.getLogger(M18BomHeaderLookupService::class.java)

    private val fetchListApi = "/search/search"

    open fun findM18IdByHeaderCode(headerCode: String): Long? {
        val trimmed = headerCode.trim()
        if (trimmed.isEmpty()) return null
        val conds = "(code=equal=$trimmed)"
        val listResponse = try {
            apiCallerService.get<M18BomListResponse, M18CommonListRequest>(
                fetchListApi,
                M18CommonListRequest(
                    stSearch = StSearchType.BOM.value,
                    params = null,
                    conds = conds,
                ),
            ).block()
        } catch (e: Exception) {
            logger.warn("(findM18IdByHeaderCode) M18 search failed code=$trimmed: ${e.message}")
            null
        }
        return listResponse?.values?.firstOrNull()?.id?.takeIf { it > 0L }
    }
}
