package com.tashow.cloud.app.mq.producer.buriedPoint;
import com.tashow.cloud.app.mq.message.BuriedMessages;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.UUID;

/**
 * 埋点消息生产者
 */
@Slf4j
@Component
public class BuriedPointProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 异步发送完整的埋点消息，并确保消息已被broker接收
     */
    @SneakyThrows
    public void asyncSendMessage(BuriedMessages message) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
       // final CompletableFuture<Boolean> confirmFuture = new CompletableFuture<>();
        log.info("[埋点] 异步准备发送消息: {}", message);
        correlationData.getFuture().whenComplete((confirm, ex) -> {
            log.info("[埋点] 异步消息发送确认回调: {}", message);
            if (ex != null) {
                log.error("[埋点] 异步消息发送异常: {}", ex.getMessage(), ex);
              //  confirmFuture.completeExceptionally(ex);
            } else if (confirm != null && confirm.isAck()) {
                log.info("[埋点] 异步消息发送成功: {}", message);
               // confirmFuture.complete(true);
            } else {
                log.warn("[埋点] 异步消息发送未被ACK");
//confirmFuture.complete(false);
            }
        });
        rabbitTemplate.convertAndSend(BuriedMessages.EXCHANGE, BuriedMessages.ROUTING_KEY, message, correlationData);
        log.info("[埋点] 异步消息发送完成: {}", message);
      //  return null;
    }
} 