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.List;
import java.util.Map;

/**
 * GUARDiA ITSM API 클라이언트.
 *
 * <p>고객 문의(CS)를 ITSM SR로 자동 생성한다. 모든 응답은
 * {@link ItsmSecuritySanitizer#clean(Object)}로 자격증명을 제거한 뒤 반환한다.
 * 실패 시 빈 Map/List 반환, 스택트레이스 미노출 (요약 로그만).
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ItsmClient {

    @Value("${guardia.itsm-url:http://localhost:9001}")
    private String itsmUrl;

    private final WebClient.Builder webClientBuilder;

    private WebClient client() {
        return webClientBuilder.baseUrl(itsmUrl).build();
    }

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

    /**
     * CS 문의 → ITSM SR 생성.
     *
     * @return 생성된 SR ID, 실패 시 null
     */
    public String createSr(String title, String content, String priority) {
        Map<String, Object> payload = Map.of(
            "title", title,
            "content", content,
            "priority", priority == null ? "MEDIUM" : priority,
            "source", "MALL"
        );
        Map<String, Object> result = call("/api/tasks", HttpMethod.POST, payload);
        Object id = result.getOrDefault("sr_id", result.get("id"));
        return id != null ? String.valueOf(id) : null;
    }

    /** SR 상태 조회. */
    public Map<String, Object> getSr(String srId) {
        return call("/api/tasks/" + srId, HttpMethod.GET, null);
    }
}
