using MongoDB.Bson;
using System.Collections.Concurrent;

namespace Insight.Web.Models;

public class ChatSession
{
    public ObjectId Id { get; } = ObjectId.GenerateNewId();
    public IEnumerable<ChatUser> Members { get; }
    public ConcurrentBag<ChatMessage> Messages { get; } = new();

    private readonly Func<ChatSession, ChatMessage, CancellationToken, Task> OnMessageSent;

    public ChatSession(IEnumerable<ChatUser> members, Func<ChatSession, ChatMessage, CancellationToken, Task> onMessageSent)
    {
        Members = members;
        OnMessageSent = onMessageSent;
    }

    public async Task SendMessage(ChatUser sender, string message, CancellationToken cancellationToken)
    {
        var cm = new ChatMessage
        {
            SenderId = sender.Uid,
            Message = message
        };

        Messages.Add(cm);

        await OnMessageSent(this, cm, cancellationToken);
    }
}