using System.Text;
using EasyNetQ.Consumer;
using Newtonsoft.Json;

namespace adas_core.Infrastructure.Utils;

public class RabbitIErrorMessageSerializer : IErrorMessageSerializer
{
    public byte[]? Deserialize(string messageBody)
    {
        var unescapedJsonString = JsonConvert.DeserializeObject<string>(messageBody);

        return unescapedJsonString != null ? Encoding.UTF8.GetBytes(unescapedJsonString) : null;
    }

    public string? Serialize(byte[] messageBody)
    {
        var stringifiedMsgBody = Encoding.UTF8.GetString(messageBody);

        try
        {
            return JsonConvert.DeserializeObject<string>(stringifiedMsgBody);
        }
        catch (Exception)
        {
            return stringifiedMsgBody;
        }
    }
}