package cn.sikey.websocket.util;

import cn.sikey.websocket.message.Message;
import cn.sikey.websocket.message.TestTextMessage;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.experimental.UtilityClass;

/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: MessageConverterUtil
 */
@UtilityClass
public class MessageConverterUtil {
    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 空字段也可以序列化
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  // 空对象也可以序列化
    }


    /**
     * 转换成 mq 的消息
     *
     * @param message 消息
     * @return mq 消息
     */
    public Object toMessaging(Message message) {
        return switch (message.getType()) {
            case HEARTBEAT_MESSAGES, ACK_MESSAGES -> null;
            case TEST_TEXT_MESSAGE -> convertChatTextMessage(message);
        };
    }

    private TestTextMessage convertChatTextMessage(Message message) {
        TestTextMessage messaging = new TestTextMessage();
        messaging.setMsgId(message.getId().getId())
                .setMsgType(message.getType())
                .setRecvId(message.getReceiverId().getFirst())
                .setSenderId(message.getSenderId())
                .setSendTime(message.getSendTime());

        messaging.setContent(
                objectMapper.convertValue(message.getContent(), TestTextMessage.TestTextMessageContent.class));
        return messaging;
    }

}
