package com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Component
public class RestTemplateUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateUtil.class);
    private static final RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
        // UTF-8 인코딩 설정
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    public static String callNlpApi(String path, String body, HttpMethod method) {
        return callNlpApi(path, null, body, method);
    }

    public static String callNlpApi(String path, String query, String body, HttpMethod method) {
        if (path == null || "null".equalsIgnoreCase(path)) path = "";
        if (query == null) {
            query = "";
        } else if (!"".equals(query) && !query.startsWith("?")) {
            query = "?" + query;
        }

        // header set
        MultiValueMap<String, String> header = new HttpHeaders();
        header.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);

        String url = "";
        if (!path.startsWith("http")) {
            url = path + query;
        } else {
            url = path + query;
        }

        try {
            LOGGER.info("CALLBOT >>> NLP : " + body);
            LOGGER.info("CALL NLP API: " + url);
            ResponseEntity<String> response = restTemplate.exchange(url + query, method, new HttpEntity<>(body, header), String.class);
            LOGGER.info(response.getBody());
            return response.getBody();
        } catch (RestClientException e) {
            LOGGER.info(e.getMessage());
            return e.getMessage();
        }
    }
}
