package com.zioinfo.mall.integration;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Collections;
import java.util.Map;

/**
 * GUARDiA ERP API 클라이언트.
 *
 * <p>재고 동기화·정산(매입/매출 전표) 연계. 응답은 새니타이저로 정제 후 반환.
 * 실패 시 빈 Map 반환, 스택트레이스 미노출.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ErpClient {

    @Value("${guardia.erp-url:http://localhost:8003}")
    private String erpUrl;

    private final WebClient.Builder webClientBuilder;

    @SuppressWarnings("unchecked")
    public Map<String, Object> call(String path, HttpMethod method, Object body) {
        try {
            WebClient.RequestBodySpec spec = webClientBuilder.baseUrl(erpUrl).build().method(method).uri(path);
            WebClient.RequestHeadersSpec<?> headersSpec =
                (body != null && method != HttpMethod.GET) ? spec.bodyValue(body) : spec;
            Map<String, Object> result = headersSpec.retrieve()
                .bodyToMono(Map.class).map(m -> (Map<String, Object>) m).block();
            if (result == null) return Collections.emptyMap();
            return (Map<String, Object>) ItsmSecuritySanitizer.clean(result);
        } catch (Exception e) {
            log.warn("ERP 연동 일시 실패 [{} {}]: {}", method, path, e.getMessage());
            return Collections.emptyMap();
        }
    }

    /** ERP 재고 조회 (SKU 기준). */
    public Map<String, Object> getStock(String sku) {
        return call("/api/erp/inventory/" + sku, HttpMethod.GET, null);
    }

    /** ERP 매출 전표 생성 (정산 연계). */
    public Map<String, Object> postSalesVoucher(Map<String, Object> voucher) {
        return call("/api/erp/finance/sales-voucher", HttpMethod.POST, voucher);
    }
}
