using adas_core.Domain.Models.MongoModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace adas_core.Infrastructure.Utils;

/// <summary>
/// Provides a custom JSON conversion implementation for point of care data, extending the base <see cref="JsonConverter"/> functionality.
/// </summary>
/// <remarks>
/// This converter is designed to handle the serialization and deserialization logic specific to point of care entities, tailoring the behavior inherited from the <see cref="JsonConverter"/> base class.
/// </remarks>
public class CustomPointOfCareConverter : JsonConverter
{
    /// <summary>
    /// Determines whether the converter can convert the specified type. Returns <c>true</c> only when the supplied type is <see cref="PointOfCare"/>; otherwise, returns <c>false</c>.
    /// </summary>
    /// <param name="objectType">The type to evaluate for convertibility.</param>
    /// <returns><c>true</c> if <paramref name="objectType"/> equals <see cref="PointOfCare"/>; otherwise, <c>false</c>.</returns>
    public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(PointOfCare);
        }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value == null)
        {
            writer.WriteNull();
            return;
        }

        var jo = JObject.FromObject(value);
        // Aquí modificas específicamente las propiedades que necesitas
        // Por ejemplo, aplicar StringEnumConverter solo a ciertas propiedades enumeradas

        // Esto es un ejemplo, ajusta según tus necesidades
        foreach (var prop in value.GetType().GetProperties())
            if (prop.PropertyType.IsEnum)
            {
                var enumValue = prop.GetValue(value);
                if (enumValue != null) jo[prop.Name] = JToken.FromObject(enumValue.ToString() ?? string.Empty);
            }

        jo.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
        JsonSerializer serializer)
    {
        // Implementa la lógica de deserialización si es necesario
        throw new NotImplementedException();
    }
}