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

namespace adas_core.Infrastructure.Utils;

/// <summary>
/// Provides an implementation of <see cref="IErrorMessageSerializer"/> tailored for use with RabbitMQ, responsible for serializing error messages into a format suitable for transport over RabbitMQ.
/// </summary>
/// <remarks>
/// This class serves as the RabbitMQ-specific concrete realization of the <see cref="IErrorMessageSerializer"/> contract.
/// </remarks>
public class RabbitIErrorMessageSerializer : IErrorMessageSerializer
{
    /// <summary>
    /// Deserializes a JSON-encoded string by unescaping its JSON representation and converts the result to a UTF-8 byte array.
    /// Returns <c>null</c> when the deserialized string is <c>null</c>.
    /// </summary>
    /// <param name="messageBody">The JSON-encoded string to unescape and convert.</param>
    /// <returns>A UTF-8 encoded byte array of the unescaped string, or <c>null</c> if the deserialized value is <c>null</c>.</returns>
    public byte[]? Deserialize(string messageBody)
        {
            var unescapedJsonString = JsonConvert.DeserializeObject<string>(messageBody);
    
            return unescapedJsonString != null ? Encoding.UTF8.GetBytes(unescapedJsonString) : null;
        }

    /// <summary>
    /// Attempts to deserialize the UTF-8 decoded message body as a JSON string, returning the original stringified content if deserialization fails.
    /// </summary>
    /// <param name="messageBody">The raw byte array representing the message body to be deserialized.</param>
    /// <returns>The deserialized JSON string if successful; otherwise, the raw UTF-8 decoded string. Returns <see langword="null"/> if the deserialized JSON value is null.</returns>
    public string? Serialize(byte[] messageBody)
        {
            var stringifiedMsgBody = Encoding.UTF8.GetString(messageBody);
    
            try
            {
                return JsonConvert.DeserializeObject<string>(stringifiedMsgBody);
            }
            catch (Exception)
            {
                return stringifiedMsgBody;
            }
        }
}