using System;
using System.Collections.Generic;
using Knot.Shared.Kernel;

namespace Knot.Contracts.Conversations.Domain;

/// <summary>
/// Сущность папки для группировки чатов.
/// </summary>
public sealed class Folder : AggregateRoot<Guid>
{
    public string Name { get; private set; }
    public string? Icon { get; private set; }
    public bool IsDefault { get; private set; }
    public FolderType Type { get; private set; }

    public Folder(Guid id, string name, string? icon = null, bool isDefault = false, FolderType type = FolderType.Custom)
        : base(id)
    {
        Name = name;
        Icon = icon;
        IsDefault = isDefault;
        Type = type;
    }

    public void Update(string name, string? icon)
    {
        if (IsDefault) throw new InvalidOperationException("Cannot rename default folders.");
        Name = name;
        Icon = icon;
    }
}

public enum FolderType
{
    All,
    New,
    Muted,
    Custom
}

/// <summary>
/// Настройки конкретного чата для конкретного пользователя.
/// </summary>
public sealed class UserChatSettings : Entity<Guid>
{
    public Guid UserId { get; private set; }
    public Guid ChatId { get; private set; }
    
    private readonly List<Guid> _folderIds = new();
    public IReadOnlyCollection<Guid> FolderIds => _folderIds.AsReadOnly();

    public bool IsMuted { get; private set; }

    private UserChatSettings() : base(Guid.NewGuid()) { }

    public UserChatSettings(Guid userId, Guid chatId) : base(Guid.NewGuid())
    {
        UserId = userId;
        ChatId = chatId;
    }

    public static UserChatSettings Create(Guid userId, Guid chatId) => new(userId, chatId);

    public void AddToFolder(Guid folderId)
    {
        if (!_folderIds.Contains(folderId)) _folderIds.Add(folderId);
    }

    public void RemoveFromFolder(Guid folderId)
    {
        _folderIds.Remove(folderId);
    }

    public void SetMute(bool isMuted) => IsMuted = isMuted;
}

/// <summary>
/// Глобальные настройки папок пользователя.
/// </summary>
public sealed class UserFolderSettings : AggregateRoot<Guid>
{
    public Guid UserId { get; private set; }
    public List<Guid> HiddenDefaultFolderIds { get; private set; } = new();
    public List<Guid> CustomFolderIds { get; private set; } = new();

    public UserFolderSettings(Guid userId) : base(Guid.NewGuid())
    {
        UserId = userId;
    }

    public void HideFolder(Guid folderId)
    {
        if (!HiddenDefaultFolderIds.Contains(folderId)) HiddenDefaultFolderIds.Add(folderId);
    }

    public void ShowFolder(Guid folderId)
    {
        HiddenDefaultFolderIds.Remove(folderId);
    }
}
