package com.eactive.httpmockserver.client.controller;

import com.eactive.httpmockserver.client.dto.ApiRequestDTO;
import com.eactive.httpmockserver.client.dto.ApiResponse;
import com.eactive.httpmockserver.server.entity.Server;
import com.eactive.httpmockserver.server.entity.ServerRepository;
import com.eactive.httpmockserver.client.service.NettyApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ApiClientController {

    @Autowired
    private ServerRepository serverRepository;

    @Autowired
    private NettyApiClient nettyApiClient;

    @PostMapping("/mgmt/api/test.do")
    @ResponseBody
    public ApiResponse handleApiRequest(@RequestBody ApiRequestDTO request) {

        try {
            return nettyApiClient.handleRequest(request).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/mgmt/api_tester.do")
    public String testView(ModelMap model) {

        List<Server> servers = serverRepository.findAllByEnabledIs(true);
        model.addAttribute("servers", servers);

        return "page/tester/apiTester";
    }

}
