package com.sonic.cow.client.rtc.callback.conversation;

import com.alibaba.fastjson.JSON;
import com.sonic.cow.client.rtc.callback.rts.Subv;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @description: 会话状态消息解析
 * @author: mzc
 * @date: 2025-08-27 15:20
 **/
public class ConversationMessageParse {

    public static Conv unpack(String msg) throws Exception {
        //Base64解码
        byte[] data = Base64.getDecoder().decode(msg);
        // 验证数据长度
        if (data.length < 8) {
            throw new Exception("Data invalid");
        }
        // 验证头部
        String dataHeader = new String(data, 0, 4, StandardCharsets.UTF_8);
        if (!"conv".equals(dataHeader)) {
            throw new Exception("Header not match");
        }
        // 验证数据大小
        ByteBuffer buffer = ByteBuffer.wrap(data, 4, 4);
        int dataSize = buffer.getInt(); // BigEndian解码
        if (dataSize + 8 != data.length) {
            throw new Exception("Size not match");
        }
        // 解析JSON内容
        byte[] subData = new byte[dataSize];
        System.arraycopy(data, 8, subData, 0, dataSize);

        return JSON.parseObject(subData, Conv.class);
    }
}
