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.ApiClientFactory;
import com.eactive.testmaster.loadtest.service.VirtualUser;
import java.util.concurrent.ExecutionException;
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;

@RestController
public class ApiClientController {

    private final ApiClientFactory apiClientFactory;
    private final Validator validator;

    public ApiClientController(ApiClientFactory apiClientFactory, Validator validator) {
        this.apiClientFactory = apiClientFactory;
        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());
        }
        VirtualUser virtualUser = new VirtualUser(request.getId(), apiClientFactory);
        return virtualUser.processApiAndReturn(request);
    }

}
