package com.bonus.mq.rocket.mqtt;

import com.bonus.mq.mqtt.MqttAuth;
import com.bonus.mq.mqtt.MqttAuthCheck;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class MqttAuthController {
   private final MqttAuthCheck mqttAuthCheck;

   public MqttAuthController(MqttAuthCheck mqttAuthCheck) {
      this.mqttAuthCheck = mqttAuthCheck;
   }

   @PostMapping({"${spring.mqtt.emqx.authc-url:/mqtt/auth/authc}"})
   public MqttAuth.Authenticating.Response authenticating(@RequestBody MqttAuth.Authenticating.Request auth) {
      return this.mqttAuthCheck.authc(auth);
   }

   @PostMapping({"${spring.mqtt.emqx.authz-url:/mqtt/auth/authz}"})
   public MqttAuth.Authorizing.Response authorizing(@RequestBody MqttAuth.Authorizing.Request auth) {
      if ("*".equals(auth.getUsername())) {
         return MqttAuth.Authorizing.ALLOW;
      } else {
         auth.setTopic(auth.getTopic().replace(".", "/"));
         return this.mqttAuthCheck.authz(auth);
      }
   }
}
