package com.ffii.fpsms.m18.service

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

/**
 * Lightweight M18 vendor search — kept separate from [M18MasterDataService] to avoid a Spring cycle
 * ([M18BomForShopService] → [M18MasterDataService] → [com.ffii.fpsms.modules.master.service.BomService] → [M18BomForShopService]).
 */
@Service
open class M18VendorLookupService(
    private val apiCallerService: ApiCallerService,
) {
    private val logger: Logger = LoggerFactory.getLogger(M18VendorLookupService::class.java)

    private val fetchListApi = "/search/search"

    /** M18 vendor id for [code] scoped to [beId] (e.g. PF vs PP business entity). */
    open fun findVendorM18IdByCode(code: String, beId: String): Long? {
        val trimmed = code.trim()
        if (trimmed.isEmpty() || beId.isBlank()) return null
        val conds = "(code=equal=$trimmed)=and=(beId=equal=$beId)"
        val listResponse = try {
            apiCallerService.get<M18VendorListResponse, M18CommonListRequest>(
                fetchListApi,
                M18CommonListRequest(
                    stSearch = StSearchType.VENDOR.value,
                    params = null,
                    conds = conds,
                ),
            ).block()
        } catch (e: Exception) {
            logger.warn("(findVendorM18IdByCode) M18 search failed code=$trimmed beId=$beId: ${e.message}")
            null
        }
        return listResponse?.values?.firstOrNull()?.id?.takeIf { it > 0L }
    }
}
