package tech.easyflow.ai.documentimport.task;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tech.easyflow.common.mq.core.MQMessage;
import tech.easyflow.common.mq.core.MQProducer;

import java.math.BigInteger;
import java.util.Date;

/**
 * 文档向量化任务消息生产者。
 *
 * @author Codex
 * @since 2026-04-14
 */
@Service
public class DocumentImportIndexTaskProducer {

    private static final Logger LOG = LoggerFactory.getLogger(DocumentImportIndexTaskProducer.class);

    private final MQProducer mqProducer;

    public DocumentImportIndexTaskProducer(MQProducer mqProducer) {
        this.mqProducer = mqProducer;
    }

    /**
     * 发送向量化任务消息。
     *
     * @param taskId 任务 ID
     */
    public void send(BigInteger taskId) {
        DocumentImportTaskMessage event = new DocumentImportTaskMessage();
        event.setTaskId(taskId);
        event.setOccurredAt(new Date());

        MQMessage message = new MQMessage();
        message.setMessageId("index-" + taskId);
        message.setTopic(DocumentImportTaskMqConstants.INDEX_TOPIC);
        message.setKey(String.valueOf(taskId));
        message.setCreatedAt(event.getOccurredAt());
        message.setBody(JSON.toJSONString(event));
        LOG.info("准备投递文档向量化 MQ 消息: topic={}, taskId={}, messageId={}",
            message.getTopic(), taskId, message.getMessageId());
        String recordId = mqProducer.send(message);
        LOG.info("文档向量化 MQ 消息投递完成: topic={}, taskId={}, messageId={}, recordId={}",
            message.getTopic(), taskId, message.getMessageId(), recordId);
    }
}
