package com.remy.graphql.resolvers.query;

import com.remy.common.module.BaseDTO;
import com.remy.common.module.GoodsDTO;
import com.remy.common.module.OrderDTO;
import com.remy.common.module.UserDTO;
import com.remy.graphql.evn.RestAPIEnv;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class EntitiesQuery implements GraphQLQueryResolver {

    @Autowired
    RestAPIEnv apiEnv;

    public CompletableFuture<List<BaseDTO>> entities() {
        return CompletableFuture.supplyAsync(() -> {
            List<BaseDTO> dto = new ArrayList<>();
            dto.addAll(new RestTemplate().exchange(
                    apiEnv.getOrdersEndpoint(),
                    HttpMethod.GET,
                    new HttpEntity(null),
                    new ParameterizedTypeReference<List<OrderDTO>>() {
                    }).getBody());
            dto.addAll(
                    new RestTemplate().exchange(
                            apiEnv.getGoodsEndpoint(),
                            HttpMethod.GET,
                            new HttpEntity(null),
                            new ParameterizedTypeReference<List<GoodsDTO>>() {
                            }).getBody());
            dto.addAll(
                    new RestTemplate().exchange(
                            apiEnv.getUsersEndpoint(),
                            HttpMethod.GET,
                            new HttpEntity(null),
                            new ParameterizedTypeReference<List<UserDTO>>() {
                            }).getBody());
            return dto;
        });
    }
}
