package tech.easyflow.chatlog.service;

import org.springframework.stereotype.Component;
import tech.easyflow.chatlog.domain.entity.ChatPersistDeadLetter;
import tech.easyflow.chatlog.domain.event.ChatPersistEvent;
import tech.easyflow.chatlog.mapper.ChatPersistDeadLetterMapper;
import tech.easyflow.chatlog.support.ChatConstants;
import tech.easyflow.chatlog.support.ChatJsonSupport;
import tech.easyflow.common.mq.core.MQDeadLetterHandler;
import tech.easyflow.common.mq.core.MQMessage;

import java.util.Date;

@Component
public class ChatPersistDeadLetterService implements MQDeadLetterHandler {

    private final ChatPersistDeadLetterMapper deadLetterMapper;
    private final ChatJsonSupport chatJsonSupport;

    public ChatPersistDeadLetterService(ChatPersistDeadLetterMapper deadLetterMapper,
                                        ChatJsonSupport chatJsonSupport) {
        this.deadLetterMapper = deadLetterMapper;
        this.chatJsonSupport = chatJsonSupport;
    }

    @Override
    public boolean supports(String topic) {
        return ChatConstants.CHAT_PERSIST_TOPIC.equals(topic);
    }

    @Override
    public void handle(MQMessage message, String reason) {
        Date now = new Date();
        ChatPersistEvent event = chatJsonSupport.fromJson(message.getBody(), ChatPersistEvent.class);

        ChatPersistDeadLetter deadLetter = new ChatPersistDeadLetter();
        deadLetter.setTopic(message.getTopic());
        deadLetter.setStreamKey(message.getStreamKey());
        deadLetter.setStreamMessageId(message.getStreamMessageId());
        deadLetter.setEventId(event == null ? message.getMessageId() : event.getEventId());
        deadLetter.setSessionId(event == null ? null : event.getSessionId());
        deadLetter.setPayload(message.getBody());
        deadLetter.setRetryCount(message.getRetryCount());
        deadLetter.setErrorMessage(reason);
        deadLetter.setFirstFailedAt(now);
        deadLetter.setLastFailedAt(now);
        deadLetter.setStatus("OPEN");
        deadLetter.setCreated(now);
        deadLetter.setModified(now);
        deadLetterMapper.insert(deadLetter);
    }
}
