package tech.easyflow.chatlog.service;

import org.springframework.stereotype.Component;
import tech.easyflow.chatlog.domain.event.ChatPersistEvent;
import tech.easyflow.chatlog.support.ChatConstants;
import tech.easyflow.chatlog.support.ChatJsonSupport;
import tech.easyflow.common.mq.config.MQProperties;
import tech.easyflow.common.mq.core.MQConsumerHandler;
import tech.easyflow.common.mq.core.MQMessage;
import tech.easyflow.common.mq.core.MQSubscription;

import java.util.ArrayList;
import java.util.List;

@Component
public class ChatPersistEventConsumer implements MQConsumerHandler {

    private final MQProperties mqProperties;
    private final ChatJsonSupport chatJsonSupport;
    private final ChatPersistMySqlApplyService applyService;

    public ChatPersistEventConsumer(MQProperties mqProperties,
                                    ChatJsonSupport chatJsonSupport,
                                    ChatPersistMySqlApplyService applyService) {
        this.mqProperties = mqProperties;
        this.chatJsonSupport = chatJsonSupport;
        this.applyService = applyService;
    }

    @Override
    public MQSubscription subscription() {
        MQSubscription subscription = new MQSubscription();
        subscription.setTopic(ChatConstants.CHAT_PERSIST_TOPIC);
        subscription.setConsumerGroup(ChatConstants.CHAT_PERSIST_GROUP);
        subscription.setShardCount(Math.max(mqProperties.getRedis().getChatPersistShardCount(), 1));
        return subscription;
    }

    @Override
    public void handle(List<MQMessage> messages) {
        List<ChatPersistEvent> events = new ArrayList<>(messages.size());
        for (MQMessage message : messages) {
            ChatPersistEvent event = chatJsonSupport.fromJson(message.getBody(), ChatPersistEvent.class);
            if (event != null) {
                events.add(event);
            }
        }
        applyService.apply(events);
    }
}
