package com.remy.graphql.resolvers.query;

import com.remy.common.module.GoodsDTO;
import com.remy.graphql.evn.RestAPIEnv;
import graphql.kickstart.tools.GraphQLQueryResolver;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.concurrent.CompletableFuture;

import static java.util.concurrent.CompletableFuture.supplyAsync;

@Component
@Slf4j
public class GoodsQuery implements GraphQLQueryResolver {

    @Autowired
    RestAPIEnv apiEnv;

    public CompletableFuture<List<GoodsDTO>> goodsList() {
        log.info("start query goods list");
        return supplyAsync(() ->
                new RestTemplate().exchange(
                        apiEnv.getGoodsEndpoint(),
                        HttpMethod.GET,
                        new HttpEntity(null),
                        new ParameterizedTypeReference<List<GoodsDTO>>() {
                        }).getBody());
    }

    public CompletableFuture<GoodsDTO> goods(String serialNo) {
        log.info("start query goods by serialNo");
        return supplyAsync(() ->
                new RestTemplate().getForObject(apiEnv.getGoodsEndpoint() + serialNo, GoodsDTO.class));
    }
}
