using MongoDB.Bson;
using Newtonsoft.Json;

namespace adas_core.Domain.Utils;

public class ObjectIdConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value is ObjectId objectId)
            // Serializa el ObjectId como un string
            writer.WriteValue(objectId.ToString());
        else
            writer.WriteNull();
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue,
        JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.String)
        {
            var stringValue = reader.Value as string;
            // Verifica si el valor es el valor predeterminado de ObjectId
            if (!string.IsNullOrEmpty(stringValue) &&
                stringValue != "000000000000000000000000" &&
                ObjectId.TryParse(stringValue, out var oid))
                return oid;
        }

        // Nullables reciben null, no-null vuelven Empty
        if (objectType == typeof(ObjectId))
            return ObjectId.Empty;
        // Retorna null o ObjectId.Empty para manejar el valor predeterminado de ObjectId
        return null;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(ObjectId).IsAssignableFrom(objectType);
    }
}