using adas_core.Domain.Models.MongoModels;
using adas_core.Infrastructure.Utils.MongoMaps.Interfaz;
using MongoDB.Bson.Serialization;

namespace adas_core.Infrastructure.Utils.MongoMaps;

/// <summary>
/// Represents an entity map contributor that provides authentication-related mapping logic.
/// </summary>
public class AuthMapContributor : IEntityMapContributor
{
    /// <summary>
    /// Registers BSON class maps for the <see cref="User"/> and <see cref="Authorization"/> types when no class map has been registered yet, configuring field serialization rules such as ignoring null or empty values, mapping the identifier to the "_id" element name, and unmapping navigation properties not intended for persistence.
    /// </summary>
    public void RegisterMaps()
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(User)))
                BsonClassMap.RegisterClassMap<User>(cm =>
                {
                    cm.AutoMap();
                    cm.MapMember(c => c.Password)
                        .SetIgnoreIfNull(true)
                        .SetShouldSerializeMethod(obj => !string.IsNullOrEmpty(((User)obj).Password));
                    cm.MapIdMember(c => c.Id).SetElementName("_id");
                    cm.MapMember(c => c.LockExpirationDate)
                        .SetIgnoreIfNull(true);
                    cm.MapMember(c => c.Authorization).SetElementName("Authorization")
                        .SetShouldSerializeMethod(_ => false);
                });
    
            if (!BsonClassMap.IsClassMapRegistered(typeof(Authorization)))
                BsonClassMap.RegisterClassMap<Authorization>(cm =>
                {
                    cm.AutoMap();
    
                    cm.MapIdMember(c => c.Id).SetElementName("_id");
                    cm.MapMember(c => c.UnitId).SetIgnoreIfNull(true);
                    cm.UnmapProperty(c => c.User);
                    cm.UnmapProperty(c => c.Display);
                    cm.UnmapProperty(c => c.Unit);
                });
        }
}