package service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.invoke.MethodHandles;
import java.util.List;

/**
 * @author Evgenii Malkov
 */
@Service
public class ConfigExecutorService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private final RestTemplate restTemplate;
    private final String url;

    public ConfigExecutorService(@Autowired RestTemplate restTemplate,
                                 @Value("${config.data.executor.url}") String url) {
        this.restTemplate = restTemplate;
        this.url = url;
    }

    public void call(String methodPath, List<String> ids) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<List<String>> entity = new HttpEntity<>(ids, headers);
        LOGGER.info("Starts call config executor service with method: {}, for ids: {}", methodPath, ids);
        try {
            ResponseEntity<Object> response = restTemplate.exchange(url.concat(methodPath), HttpMethod.POST, entity, Object.class);
            LOGGER.info("Method: {}, executed with status: {}, for ids:{}", methodPath, response.getStatusCode().value(), ids);
        } catch (Exception e) {
            throw new RuntimeException(String.format(
                    "Failed call config executor service method: %s for ids: %s with error", methodPath, ids), e);
        }
    }
}
