package com.sikey.wa04.business.infrastructure.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestTemplateConfig {

    @Bean
    @Primary
    public RestTemplate restTemplate(ObjectMapper objectMapper) {
        // 创建MappingJackson2HttpMessageConverter，将其关联ObjectMapper
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);

        // 创建一个HttpMessageConverter列表，添加刚创建的Jackson转换器
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        converters.add(converter);

        // 创建SimpleClientHttpRequestFactory，用于设置请求相关属性（可选步骤）
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // 创建RestTemplate实例，并设置消息转换器和请求工厂（如果有的话）
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setMessageConverters(converters);
        return restTemplate;
    }

}
