package de.assecutor.votianlt.mqtt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;

/**
 * Simple MQTT publishing helper to send JSON payloads.
 *
 * Note: In environments where Spring Integration MQTT is unavailable (e.g.,
 * offline CI), this implementation degrades to a no-op publisher that logs the
 * intended message.
 */
public interface MqttPublisher {
    void publishAsJson(String topic, Object payload);

    void publishAsJson(String topic, Object payload, boolean retained);
}

@Component
@Slf4j
class MqttPublisherImpl implements MqttPublisher {

    private final ObjectMapper objectMapper;
    private final MqttV5ClientManager clientManager;

    public MqttPublisherImpl(@Lazy MqttV5ClientManager clientManager) {
        this.clientManager = clientManager;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());
    }

    @Override
    public void publishAsJson(String topic, Object payload) {
        publishAsJson(topic, payload, false);
    }

    @Override
    public void publishAsJson(String topic, Object payload, boolean retained) {
        try {
            String json = (payload instanceof String s) ? s : objectMapper.writeValueAsString(payload);
            byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8);
            // Default QoS 2
            clientManager.publish(topic, bytes, 2, retained);

            // Log all published JSON documents
            log.info("=== MQTT JSON PUBLISHED ===");
            log.info("Topic: {}", topic);
            log.info("Retained: {}", retained);
            log.info("JSON Data: {}", json);
            log.info("=== END MQTT PUBLISH ===");

        } catch (Exception e) {
            log.error("Failed to serialize/publish MQTT message for topic {}: {}", topic, e.getMessage(), e);
        }
    }
}
