package tech.easyflow.chatlog.service;

import org.springframework.stereotype.Service;
import tech.easyflow.chatlog.domain.event.ChatPersistEvent;
import tech.easyflow.chatlog.support.ChatConstants;
import tech.easyflow.chatlog.support.ChatJsonSupport;
import tech.easyflow.common.mq.core.MQMessage;
import tech.easyflow.common.mq.core.MQProducer;

@Service
public class ChatPersistEventProducer {

    private final MQProducer mqProducer;
    private final ChatJsonSupport chatJsonSupport;

    public ChatPersistEventProducer(MQProducer mqProducer, ChatJsonSupport chatJsonSupport) {
        this.mqProducer = mqProducer;
        this.chatJsonSupport = chatJsonSupport;
    }

    public void send(ChatPersistEvent event) {
        MQMessage message = new MQMessage();
        message.setMessageId(event.getEventId());
        message.setTopic(ChatConstants.CHAT_PERSIST_TOPIC);
        message.setKey(event.getSessionId() == null ? event.getEventId() : event.getSessionId().toString());
        message.setBody(chatJsonSupport.toJson(event));
        message.setCreatedAt(event.getOccurredAt());
        if (event.getTraceId() != null && !event.getTraceId().isBlank()) {
            message.getHeaders().put("traceId", event.getTraceId());
        }
        mqProducer.send(message);
    }
}
