using System.IO;
using System.Threading.Tasks;
using audit_logs.Services.Interfaces;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;

namespace audit_logs.Services
{
    public class DeepCopyService : IDeepCopyService
    {
        public Task<T> DeepCopyAsync<T>(T source)
        {
            T copy;
            using (var stream = new MemoryStream())
            {
                // Serializa el objeto al stream en formato BSON
                using (var writer = new BsonBinaryWriter(stream))
                {
                    BsonSerializer.Serialize(writer, source);
                }
                
                // Reinicia la posición del stream para leer desde el inicio
                stream.Seek(0, SeekOrigin.Begin);
                
                // Deserializa el objeto desde el stream
                using (var reader = new BsonBinaryReader(stream))
                {
                    copy = BsonSerializer.Deserialize<T>(reader);
                }
            }
            return Task.FromResult(copy);
        }
    }
}