using Knot.Contracts.Conversations.Domain;
using Knot.Shared.Kernel;

using Knot.Contracts.Conversations.Application.Abstractions;

namespace Knot.Modules.Conversations.Application.Chats.Create;

/// <summary>
/// Команда для создания чата.
/// </summary>
public sealed record CreateChatCommand(
    string Name,
    ChatType Type,
    List<Guid> MemberIds) : ICommand<Guid>;

public sealed class CreateChatCommandHandler : ICommandHandler<CreateChatCommand, Guid>
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _unitOfWork;

    public CreateChatCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork unitOfWork)
    {
        _chatRepository = chatRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result<Guid>> Handle(CreateChatCommand request, CancellationToken cancellationToken)
    {
        var chat = Chat.Create(request.Name, request.Type);

        for (int i = 0; i < request.MemberIds.Count; i++)
        {
            var userId = request.MemberIds[i];
            var role = (i == 0) ? ChatRole.Owner : ChatRole.Member;
            chat.AddMember(userId, role);
        }

        _chatRepository.Add(chat);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Result.Success(chat.Id);
    }
}

