package xtools.boot.mq.base.init;

import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.NonNull;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import xtools.base.config.BaseParams;
import xtools.base.exception.CommonException;
import xtools.boot.api.enums.BootError;
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.handle.BaseMessageHandle;
import xtools.boot.mq.base.handle.BaseMqHandle;
import xtools.core.CollectionUtils;
import xtools.core.enums.LogLevel;

import java.util.Collection;
import java.util.Objects;


/**
 * <p>Title : InitMq</p>
 * <p>Description : InitMq</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/2 14:13
 */
@Slf4j
@Component
@Order(BaseParams.CP_NUM50)
public class InitMq implements ApplicationRunner {

    @Override
    public void run(@NonNull ApplicationArguments args) {
        ScopedValue.where(LogTrackHolder.getScoped(), LogTrackHolder.newMain()).run(() -> {
            try {
                init();
            } catch (Exception e) {
                LogBus.init(LogLevel.ERROR, LogBusBaseType.MQ).title("初始化异常").error(e).save();
            }
        });

    }

    /**
     * 初始化
     */
    @SuppressWarnings("rawtypes")
    private void init() {
        BaseMqHandle mqHandle = SpringContextUtils.getBeanDefNull(BaseMqHandle.class);
        if (Objects.isNull(mqHandle)) {
            throw CommonException.create(BootError.MQ, "没有找到MQ处理适配器,请添加对应Jar包");
        }

        Collection<BaseMessageHandle> beanList = SpringContextUtils.getBeanList(BaseMessageHandle.class);
        if (CollectionUtils.isEmpty(beanList)) {
            log.info("没有找到MQ的消息处理适配器");
            return;
        }
        beanList.forEach(item -> {
            // 获取队列名称
            String queueName = item.queue().queue();
            try {
                mqHandle.initQueue(queueName);
                mqHandle.addListen(queueName, item, item.listenerMethod(), item.params());
                log.info("消息队列监听[{}]初始化成功", queueName);
            } catch (Exception e) {
                LogBus.init(LogLevel.ERROR, LogBusBaseType.MQ).title("初始化" + queueName + "异常").error(e).save();
            }
        });
    }
}
