package com.yupi.project.config;

import com.yupi.project.config.properties.MqttLoggerProperties;
import com.yupi.project.config.properties.MqttProperties;
import com.yupi.project.mqtt.MqttLoggerCallbackHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.UUID;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class MqttLoggerClientConfig {

    private final MqttProperties mainMqttProperties;
    private final MqttLoggerProperties mqttLoggerProperties;
    private final MqttConnectOptions mqttConnectOptions;

    @Bean(name = "mqttLoggerClient")
    @Lazy
    public MqttClient mqttLoggerClient(@Qualifier("mqttLoggerCallbackHandler") MqttLoggerCallbackHandler loggerCallbackHandler)
            throws MqttException {
        if (!mqttLoggerProperties.isEnabled()) {
            log.info("MQTT Logger Client is disabled via configuration.");
            return null;
        }

        String clientId = mqttLoggerProperties.getClientIdPrefix() + UUID.randomUUID().toString().replace("-", "");
        log.info("Initializing MQTT Logger Client with Broker URL: {} and Client ID: {}", mainMqttProperties.getBrokerUrl(), clientId);

        MqttClient client = new MqttClient(mainMqttProperties.getBrokerUrl(), clientId, new MemoryPersistence());
        client.setCallback(loggerCallbackHandler);
        loggerCallbackHandler.setMqttClient(client);
        return client;
    }
} 