package be.naaturel.boardmateapi.controllers;

import be.naaturel.boardmateapi.common.exceptions.ServiceException;
import be.naaturel.boardmateapi.services.MqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("/broker")
public class BrokerController {

    private final MqttService service;

    @Autowired
    public BrokerController(MqttService service){
        this.service = service;
    }

    @PostMapping("/publish/{topic}")
    public ResponseEntity<ResponseBody<?>> publish(@PathVariable String topic, @RequestBody String message){
        ResponseBody<?> body = ResponseBody.createEmpty();
        try {
            service.subscribe(topic);
            service.publish(topic, message);
            body.setSuccess(true);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(body);
        } catch (ServiceException se){
            body.setMessage(se.getMessage());
            body.setSuccess(false);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(body);
        }
    }
}

