using Newtonsoft.Json.Linq;

namespace audit_logs.Utils;
using System.Text.Json;

public static class JsonConverter
{
    /// <summary>
    /// Converts an object to a JSON string.
    /// </summary>
    /// <param name="obj">the object to be converted</param>
    /// <returns>A JSON string representing the object</returns>
    public static string ConvertObjectToJson(object obj)
    {
        try
        {
            // Si el objeto es una cadena, asumimos que ya es JSON
            if (obj is string jsonString && IsValidJson(jsonString))
            {
                return jsonString; // No volver a serializar
            }
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
            var json = JsonSerializer.Serialize(obj);
            return json;
        }
        catch (Exception ex)
        {
            return $"Error converting object to JSON: {ex.Message}";
        }
    }
    /// <summary>
    /// Valida si una cadena es un JSON válido.
    /// </summary>
    private static bool IsValidJson(string jsonString)
    {
        try
        {
            JToken.Parse(jsonString);
            return true;
        }
        catch
        {
            return false;
        }
    }
}