package cn.reghao.tnb.content.app.util.rabbit;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.reghao.bnt.log.AppLog;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @author reghao
 * @date 2025-07-18 09:54:51
 */
public class RabbitAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    private final String app;
    private final String host;
    private final RabbitTemplate rabbitTemplate;

    public RabbitAppender(String app, String host, RabbitTemplate rabbitTemplate) {
        setName("rabbitAppender");
        this.app = app;
        this.host = host;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    protected void append(ILoggingEvent event) {
        AppLog appLog = getAppLog(event);
        String jsonPayload = JsonConverter.objectToJson(appLog);

        String routingKey = "tnb.log.app";
        rabbitTemplate.convertAndSend(routingKey, jsonPayload);
    }

    private AppLog getAppLog(ILoggingEvent event) {
        String requestId = event.getMDCPropertyMap().get("request_id");
        long timestamp = event.getTimeStamp();
        String level = event.getLevel().toString();
        String thread = event.getThreadName();
        String logger = event.getLoggerName();
        String message = event.getFormattedMessage();
        return new AppLog(requestId, app, host, timestamp, level, thread, logger, message);
    }
}
