package com.bsmlab.dfx.dfxconsole.app.communicate;

import com.bsmlab.dfx.agent.listener.dto.AckDto;
import com.bsmlab.dfx.agent.support.ServletUtils;
import com.bsmlab.dfx.dfxconsole.app.communicate.service.ListenerService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@Slf4j
@RequiredArgsConstructor
public class ListenerController {
    private final ListenerService listenerService;

    /**
     * 에이전트로부터 메시지를 수신한다.
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/listen")
    public ResponseEntity<AckDto> listener(HttpServletRequest request) {
        AckDto ackDto = AckDto.builder().build();
        try {
            String bodyString = ServletUtils.getBodyString(request);
            ackDto = listenerService.receiveMessage(bodyString);
        } catch (IOException e) {
            ackDto = AckDto.builder().result(AckDto.ResultType.RECEIVE_FAIL).resultText(e.getLocalizedMessage()).messageUuid("").build();
        }
        return ResponseEntity.ok().body(ackDto);
    }

    /**
     * 에이전트로부터 상태 점검 등 command 수신한다.
     */
    @PostMapping(value = "/command")
    public ResponseEntity<AckDto> command(HttpServletRequest request) {
        AckDto ackDto = AckDto.builder().build();
        try {
            String bodyString = ServletUtils.getBodyString(request);
            ackDto = listenerService.receiveCommand(bodyString);
        } catch (IOException e) {
            ackDto = AckDto.builder().result(AckDto.ResultType.RECEIVE_FAIL).resultText(e.getLocalizedMessage()).messageUuid("").build();
        }
        return ResponseEntity.ok().body(ackDto);
    }
}