package xtools.boot.mq.base.utils;

import com.alibaba.fastjson2.JSONObject;
import xtools.boot.api.exection.BizError;
import xtools.boot.api.model.dto.log.LogTrack;
import xtools.boot.core.utils.SpringContextUtils;
import xtools.boot.log.LogBus;
import xtools.boot.log.enums.LogBusBaseType;
import xtools.boot.log.holder.LogTrackHolder;
import xtools.boot.mq.base.enums.MqEnums;
import xtools.boot.mq.base.handle.BaseMqHandle;
import xtools.boot.thread.utils.VirtualThreadTaskUtils;
import xtools.core.enums.LogLevel;

import java.util.Objects;

/**
 * <p>Title : MqBus</p>
 * <p>Description : MqBus</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/2/12 10:00
 */
public class MqBus {

    /**
     * 推送到消息队列
     *
     * @param mq   队列
     * @param data 数据
     */
    public static void push(MqEnums mq, Object data) {
        BaseMqHandle mqHandle = SpringContextUtils.getBeanDefNull(BaseMqHandle.class);
        if (Objects.isNull(mqHandle)) {
            throw new BizError("没有找到MQ处理适配器,请添加对应Jar包");
        }
        // 是否保存日志
        boolean saveLog = mq.saveLog();
        LogTrack logTrack;
        if (saveLog) {
            logTrack = LogTrackHolder.getDefNull();
            if (Objects.isNull(logTrack)) {
                saveLog = false;
            } else {
                saveLog = logTrack.save();
            }
        }
        if (saveLog) {
            VirtualThreadTaskUtils.execute(() -> {
                LogTrack track = LogTrackHolder.get();
                JSONObject message = MqMessageUtils.to(data, track);
                LogBus.init(LogLevel.INFO, LogBusBaseType.MQ, track).title("MQ推送").data(message).save();
                mqHandle.push(mq.queue(), message.toString());
            });
        } else {
            VirtualThreadTaskUtils.simple(() -> mqHandle.push(mq.queue(), MqMessageUtils.to(data, null).toString()));
        }
    }

}
