package com.shzg.project.worn.sensor.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * MQTT 消息发布客户端
 *
 * 所有下行统一使用：
 * JSON + Base64
 */
@Slf4j
@Component
public class MqttPublishClient {

    private final MqttClient mqttClient;

    public MqttPublishClient(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    // ================== 标准下行发送 ==================
    public void publish(String topic, String payload) {
        publish(topic, payload, 1, false);
    }

    public void publish(String topic, String payload, int qos, boolean retained) {
        checkClient();

        try {
            MqttMessage msg = new MqttMessage(payload.getBytes(StandardCharsets.UTF_8));
            msg.setQos(qos);
            msg.setRetained(retained);

            mqttClient.publish(topic, msg);

            log.info("[MQTT] 下行发送成功 topic={}, payload={}, qos={}, retained={}",
                    topic, payload, qos, retained);

        } catch (Exception e) {
            log.error("[MQTT] 下行发送失败 topic=" + topic + ", payload=" + payload, e);
            throw new RuntimeException("MQTT发送失败", e);
        }
    }

    // ================== 客户端校验 ==================
    private void checkClient() {
        if (mqttClient == null) {
            throw new IllegalStateException("MQTT客户端未初始化（mqtt.enabled=false）");
        }
        if (!mqttClient.isConnected()) {
            throw new IllegalStateException("MQTT客户端未连接到Broker");
        }
    }
}