using SumaTube.Infra.MongoDB;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson;
using SumaTube.Domain;
using SumaTube.Domain.Entities.UserPlan;

namespace SumaTube.Infra.MongoDB
{
    public static class MongoConfig
    {
        public static void Configure()
        {
            var conventionPack = new ConventionPack { new IgnoreIfNullConvention(true) };
            ConventionRegistry.Register("IgnoreIfNull", conventionPack, t => true);

            if (!BsonClassMap.IsClassMapRegistered(typeof(PersonUser)))
            {
                BsonClassMap.RegisterClassMap<PersonUser>(cm =>
                {
                    cm.MapIdProperty(p => p.Id)
                      .SetSerializer(new StringSerializer(BsonType.ObjectId))
                      .SetIdGenerator(StringObjectIdGenerator.Instance);

                    cm.MapProperty(p => p.Username);
                    cm.MapProperty(p => p.Name);
                    cm.MapProperty(p => p.Email);
                    cm.MapProperty(p => p.DateChanged);
                    cm.MapProperty(p => p.IsProfileCompleted);
                    cm.MapProperty(p => p.CountryId);
                    cm.MapProperty(p => p.BusinessAreaId);
                    cm.MapProperty(p => p.DesiredName);
                    cm.MapProperty(p => p.CreatedAt);
                    cm.MapProperty(p => p.Plano);
                    cm.MapProperty(p => p.PastPlans);

                    cm.MapCreator(p => new PersonUser(
                        p.Id.Value,
                        p.Username,
                        p.Name,
                        p.Email,
                        p.DateChanged,
                        p.IsProfileCompleted,
                        p.CountryId,
                        p.BusinessAreaId,
                        p.DesiredName,
                        p.CreatedAt,
                        p.Plano,
                        p.PastPlans
                    ));

                    cm.AutoMap();
                });
            }

            // Configure também as classes ValueObject se necessário
            ConfigureValueObjects();
        }

        private static void ConfigureValueObjects()
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(Name)))
            {
                BsonClassMap.RegisterClassMap<Name>(cm =>
                {
                    cm.AutoMap();
                    cm.MapCreator(n => new Name(n.FirstName, n.LastName));
                });
            }

            // Adicione mapeamento para outros value objects conforme necessário
        }
    }
}
