package com.remy.graphql.resolvers.query;

import com.remy.common.module.UserDTO;
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 UserQuery implements GraphQLQueryResolver {

    @Autowired
    RestAPIEnv apiEnv;

    public CompletableFuture<List<UserDTO>> userList() {
        log.info("start query orderList");
        return supplyAsync(() ->
                new RestTemplate().exchange(
                        apiEnv.getUsersEndpoint(),
                        HttpMethod.GET,
                        new HttpEntity(null),
                        new ParameterizedTypeReference<List<UserDTO>>() {
                        }).getBody());
    }

    public CompletableFuture<UserDTO> userQuery(String username) {
        log.info("start query order by goods serial no");
        return supplyAsync(() ->
                new RestTemplate().getForObject(apiEnv.getUsersEndpoint() + "query?username=" + username, UserDTO.class));
    }

    public CompletableFuture<UserDTO> userInfo(Long userID) {
        log.info("start query user by user id");
        return supplyAsync(() ->
                new RestTemplate().getForObject(apiEnv.getUsersEndpoint() + userID, UserDTO.class));
    }
}
