package com.zioinfo.mes.integration;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * GUARDiA ITSM 연계 — 설비 장애/비가동을 ITSM SR로 자동 생성한다.
 *
 * <p>응답은 {@link GuardiaHttpClient}가 자격증명을 새니타이즈한다.
 */
@Component
@RequiredArgsConstructor
public class ItsmClient {

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

    private final GuardiaHttpClient http;

    /**
     * 설비 장애/비가동 → 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", "MES"
        );
        Map<String, Object> result = http.callMap(itsmUrl, "/api/tasks", HttpMethod.POST, payload);
        Object id = result.getOrDefault("sr_id", result.get("id"));
        return id != null ? String.valueOf(id) : null;
    }

    public boolean available() {
        Map<String, Object> r = http.callMap(itsmUrl, "/actuator/health", HttpMethod.GET, null);
        return !r.isEmpty();
    }
}
