using MemeVault.Domain.Enums; using MemeVault.Domain.Events; using MemeVault.Domain.Exceptions; namespace MemeVault.Domain.Aggregates.Collection; /// /// Aggregate Root: коллекция медиа-элементов с ACL-моделью доступа. /// Каждый пользователь имеет ровно одну системную коллекцию Inbox (IsInbox = true). /// public sealed class Collection { private readonly List _members = []; private readonly List _domainEvents = []; public Guid Id { get; private set; } /// Вычисляется из CollectionMember с ролью Owner. public long OwnerTelegramId => _members.FirstOrDefault(m => m.Role == CollectionRole.Owner)?.TelegramId ?? 0L; public string Name { get; private set; } = string.Empty; public string? Description { get; private set; } public CollectionVisibility Visibility { get; private set; } /// Системная коллекция входящих. Нельзя удалить или переименовать. public bool IsInbox { get; private set; } /// Токен для доступа по ссылке (для Visibility = LinkOnly и Public). public string? ShareToken { get; private set; } public IReadOnlyList Members => _members.AsReadOnly(); public DateTimeOffset CreatedAt { get; private set; } public DateTimeOffset? UpdatedAt { get; private set; } public IReadOnlyList DomainEvents => _domainEvents.AsReadOnly(); // EF Core constructor private Collection() { } private Collection(Guid id, long ownerTelegramId, string name, string? description, bool isInbox) { Id = id; Name = name; Description = description; IsInbox = isInbox; Visibility = CollectionVisibility.Private; CreatedAt = DateTimeOffset.UtcNow; // Владелец автоматически становится членом с ролью Owner _members.Add(new CollectionMember(id, ownerTelegramId, CollectionRole.Owner)); } public static Collection Create(long ownerTelegramId, string name, string? description = null) { if (string.IsNullOrWhiteSpace(name)) throw new DomainException("Collection name cannot be empty."); if (name.Length > 100) throw new DomainException("Collection name must be 100 characters or less."); return new Collection(Guid.NewGuid(), ownerTelegramId, name, description, isInbox: false); } /// Создаёт системную коллекцию входящих для нового пользователя. public static Collection CreateInbox(long ownerTelegramId) => new(Guid.NewGuid(), ownerTelegramId, "Inbox", description: null, isInbox: true); // ── Управление участниками ───────────────────────────────────────────────── public void AddMember(long telegramId, CollectionRole role, long requestingTelegramId) { EnsureRole(requestingTelegramId, CollectionRole.Owner); if (role == CollectionRole.Owner) throw new DomainException("Cannot assign Owner role. Transfer ownership instead."); var existing = _members.FirstOrDefault(m => m.TelegramId == telegramId); if (existing is not null) { existing.ChangeRole(role); } else { _members.Add(new CollectionMember(Id, telegramId, role)); } UpdatedAt = DateTimeOffset.UtcNow; } public void RemoveMember(long telegramId, long requestingTelegramId) { EnsureRole(requestingTelegramId, CollectionRole.Owner); if (telegramId == OwnerTelegramId) throw new DomainException("Cannot remove the owner from the collection."); var member = _members.FirstOrDefault(m => m.TelegramId == telegramId) ?? throw new DomainException("Member not found."); _members.Remove(member); UpdatedAt = DateTimeOffset.UtcNow; } // ── Видимость и шаринг ──────────────────────────────────────────────────── public void SetVisibility(CollectionVisibility visibility, long requestingTelegramId) { EnsureRole(requestingTelegramId, CollectionRole.Owner); Visibility = visibility; if (visibility is CollectionVisibility.LinkOnly or CollectionVisibility.Public) { ShareToken ??= GenerateToken(); } UpdatedAt = DateTimeOffset.UtcNow; } public void Rename(string newName, long requestingTelegramId) { if (IsInbox) throw new DomainException("Cannot rename the Inbox collection."); EnsureRole(requestingTelegramId, CollectionRole.Manager); if (string.IsNullOrWhiteSpace(newName)) throw new DomainException("Collection name cannot be empty."); Name = newName.Trim(); UpdatedAt = DateTimeOffset.UtcNow; } // ── Доступ ──────────────────────────────────────────────────────────────── public bool CanView(long telegramId) { if (Visibility == CollectionVisibility.Public) return true; return _members.Any(m => m.TelegramId == telegramId); } public CollectionRole? GetRole(long telegramId) => _members.FirstOrDefault(m => m.TelegramId == telegramId)?.Role; private void EnsureRole(long telegramId, CollectionRole minimumRole) { var role = GetRole(telegramId); if (role is null || role < minimumRole) throw new DomainException($"Action requires at least {minimumRole} role."); } private static string GenerateToken() => Convert.ToBase64String(Guid.NewGuid().ToByteArray()) .Replace("/", "_").Replace("+", "-").TrimEnd('='); public void ClearDomainEvents() => _domainEvents.Clear(); }