package com.eactive.testmaster.client.controller;

import com.eactive.testmaster.client.dto.ApiRequestDTO;
import com.eactive.testmaster.client.dto.ApiResponse;
import com.eactive.testmaster.client.service.NettyApiClient;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

@RestController
public class ApiClientController {

    private final NettyApiClient nettyApiClient;
    private final Validator validator;

    public ApiClientController(NettyApiClient nettyApiClient, Validator validator) {
        this.nettyApiClient = nettyApiClient;
        this.validator = validator;
    }

    @PostMapping("/mgmt/api/test.do")
    public ApiResponse handleApiRequest(@RequestBody ApiRequestDTO request, BindingResult bindingResult) throws InterruptedException, ExecutionException {

        validator.validate(request, bindingResult);

        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        return nettyApiClient.handleRequest(request).get();
    }
}
