package com.zioinfo.mes.integration;

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

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * GUARDiA 연계 솔루션(ERP/ITSM/OCR/BI) 공용 HTTP 클라이언트.
 *
 * <p>모든 응답은 {@link ItsmSecuritySanitizer#clean(Object)}로 자격증명을 제거한 뒤 반환한다.
 * 연계 실패 시 빈 Map/List 반환(스택트레이스 미노출, 요약 로그만) — 폴백을 호출 측이 수행한다.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GuardiaHttpClient {

    private final WebClient.Builder webClientBuilder;

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

    @SuppressWarnings("unchecked")
    public List<Object> callList(String baseUrl, String path, HttpMethod method, Object body) {
        try {
            WebClient.RequestBodySpec spec = webClientBuilder.baseUrl(baseUrl).build().method(method).uri(path);
            WebClient.RequestHeadersSpec<?> headersSpec =
                (body != null && method != HttpMethod.GET) ? spec.bodyValue(body) : spec;
            List<Object> result = headersSpec.retrieve()
                .bodyToMono(List.class)
                .timeout(Duration.ofSeconds(10))
                .map(l -> (List<Object>) l)
                .block();
            if (result == null) {
                return Collections.emptyList();
            }
            return (List<Object>) ItsmSecuritySanitizer.clean(result);
        } catch (Exception e) {
            log.warn("GUARDiA 연계 일시 실패 [{} {}{}]: {}", method, baseUrl, path, e.getMessage());
            return Collections.emptyList();
        }
    }
}
