package gc.mda.kcg.domain.analysis;

import gc.mda.kcg.config.AppProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;

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

/**
 * iran 백엔드 REST 클라이언트.
 *
 * 운영 환경: https://kcg.gc-si.dev (Spring Boot + Prediction 통합)
 * 호출 실패 시 graceful degradation: null 반환 → 프론트에 빈 응답.
 *
 * 향후 prediction 이관 시 IranBackendClient를 PredictionDirectClient로 교체하면 됨.
 */
@Slf4j
@Component
public class IranBackendClient {

    private final RestClient restClient;
    private final boolean enabled;

    public IranBackendClient(AppProperties appProperties) {
        String baseUrl = appProperties.getIranBackend().getBaseUrl();
        this.enabled = baseUrl != null && !baseUrl.isBlank();
        this.restClient = enabled
                ? RestClient.builder()
                    .baseUrl(baseUrl)
                    .defaultHeader("Accept", "application/json")
                    .build()
                : RestClient.create();
        log.info("IranBackendClient initialized: enabled={}, baseUrl={}", enabled, baseUrl);
    }

    public boolean isEnabled() {
        return enabled;
    }

    /**
     * GET 호출 (Map 반환). 실패 시 null 반환.
     */
    public Map<String, Object> getJson(String path) {
        if (!enabled) return null;
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = restClient.get().uri(path).retrieve().body(Map.class);
            return body;
        } catch (RestClientException e) {
            log.debug("iran 백엔드 호출 실패: {} - {}", path, e.getMessage());
            return null;
        }
    }

    /**
     * 임의 타입 GET 호출.
     */
    public <T> T getAs(String path, Class<T> responseType) {
        if (!enabled) return null;
        try {
            return restClient.get().uri(path).retrieve().body(responseType);
        } catch (RestClientException e) {
            log.debug("iran 백엔드 호출 실패: {} - {}", path, e.getMessage());
            return null;
        }
    }
}
