package tech.easyflow.common.mq.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import tech.easyflow.common.mq.core.MQMessage;
import tech.easyflow.common.mq.core.MQMessageConverter;
import tech.easyflow.common.mq.exception.MQException;

public class JacksonMQMessageConverter implements MQMessageConverter {

    private final ObjectMapper objectMapper;

    public JacksonMQMessageConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String serialize(MQMessage message) {
        try {
            return objectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            throw new MQException("MQ 消息序列化失败", e);
        }
    }

    @Override
    public MQMessage deserialize(String payload) {
        try {
            return objectMapper.readValue(payload, MQMessage.class);
        } catch (JsonProcessingException e) {
            throw new MQException("MQ 消息反序列化失败", e);
        }
    }
}
