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 CRM API 클라이언트.
 *
 * <p>회원=고객 연계. 주문 이력을 CRM 고객 인사이트로 전달한다.
 * 응답은 새니타이저로 정제 후 반환. 실패 시 빈 Map, 스택트레이스 미노출.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CrmClient {

    @Value("${guardia.crm-url:http://localhost:8004}")
    private String crmUrl;

    private final WebClient.Builder webClientBuilder;

    @SuppressWarnings("unchecked")
    public Map<String, Object> call(String path, HttpMethod method, Object body) {
        try {
            WebClient.RequestBodySpec spec = webClientBuilder.baseUrl(crmUrl).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("CRM 연동 일시 실패 [{} {}]: {}", method, path, e.getMessage());
            return Collections.emptyMap();
        }
    }

    /** 회원 가입/주문 시 CRM 고객 upsert. */
    public Map<String, Object> upsertCustomer(Map<String, Object> customer) {
        return call("/api/crm/customers/upsert", HttpMethod.POST, customer);
    }

    /** CRM 고객 인사이트 조회. */
    public Map<String, Object> getCustomerInsight(String customerKey) {
        return call("/api/crm/customers/" + customerKey + "/insight", HttpMethod.GET, null);
    }
}
