using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
///
/// Per-user notification preferences including channel configuration,
/// language, digest schedule, and subscribed event types.
///
public class UserNotificationConfig : Entity, IAuditableEntity
{
public Guid UserId { get; private set; }
public bool EmailEnabled { get; private set; }
public string? EmailAddress { get; private set; }
public bool NtfyEnabled { get; private set; }
public string? NtfyUrl { get; private set; }
public string? NtfyTopic { get; private set; }
public string Language { get; private set; } = "fr";
public bool DailyDigest { get; private set; }
public bool WeeklyDigest { get; private set; }
public string? SubscribedEventsJson { get; private set; } // JSON array of EventType values
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
private UserNotificationConfig() { } // EF Core
public UserNotificationConfig(Guid userId)
: base(Guid.NewGuid())
{
UserId = userId;
}
public void UpdateEmail(string? emailAddress, bool enabled)
{
EmailAddress = emailAddress;
EmailEnabled = enabled;
}
public void UpdateNtfy(string? url, bool enabled, string? topic = null)
{
NtfyUrl = url;
NtfyEnabled = enabled;
if (topic is not null)
NtfyTopic = topic;
}
public void UpdateDigests(bool daily, bool weekly)
{
DailyDigest = daily;
WeeklyDigest = weekly;
}
public void SetSubscribedEvents(string? subscribedEventsJson)
{
SubscribedEventsJson = subscribedEventsJson;
}
///
/// Parses the stored JSON into a list of values.
/// Returns null if no filter is configured (meaning: receive all events).
///
public IReadOnlyList? GetSubscribedEvents()
{
if (string.IsNullOrWhiteSpace(SubscribedEventsJson))
return null;
try
{
var names = System.Text.Json.JsonSerializer.Deserialize>(SubscribedEventsJson);
if (names is null || names.Count == 0)
return null;
var result = new List();
foreach (var name in names)
{
if (Enum.TryParse(name, ignoreCase: true, out var et))
result.Add(et);
}
return result.Count > 0 ? result : null;
}
catch
{
return null;
}
}
///
/// Checks if a given EventType is subscribed (or if no filter is set, always returns true).
///
public bool IsEventTypeSubscribed(EventType? eventType)
{
if (eventType is null) return true; // System events always pass
var subscribed = GetSubscribedEvents();
return subscribed is null || subscribed.Contains(eventType.Value);
}
public void SetLanguage(string language)
{
Language = language;
}
}