using System;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using Knot.Shared.Kernel.Security;

namespace Knot.Modules.Messaging.Infrastructure.Persistence.Mongo;

public class EncryptedStringSerializer : SerializerBase<string>
{
    public static IEncryptionService? EncryptionService { get; set; }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, string value)
    {
        if (string.IsNullOrEmpty(value) || EncryptionService == null)
        {
            context.Writer.WriteString(value ?? string.Empty);
            return;
        }
        
        try
        {
            var encrypted = EncryptionService.EncryptMessage(value);
            context.Writer.WriteString(encrypted);
        }
        catch
        {
            context.Writer.WriteString(value);
        }
    }

    public override string Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var value = context.Reader.ReadString();
        if (string.IsNullOrEmpty(value) || EncryptionService == null)
        {
            return value;
        }

        try
        {
            return EncryptionService.DecryptMessage(value);
        }
        catch
        {
            // Fallback for already unencrypted, or failed to decrypt
            return value;
        }
    }
}

