using System;
using System.Threading;
using System.Threading.Tasks;
using Knot.Shared.Kernel;
using Knot.Contracts.Conversations.Domain;
using Knot.Contracts.Conversations.Application.Abstractions;
using MediatR;
using System.Linq;

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

public record UpdateChatCommand(Guid ChatId, Guid UserId, string? Name, string? Description) : ICommand<Guid>;

internal sealed class UpdateChatCommandHandler : ICommandHandler<UpdateChatCommand, Guid>
{
    private readonly IChatRepository _chatRepository;
    private readonly IChatsUnitOfWork _uow;

    public UpdateChatCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork uow)
    {
        _chatRepository = chatRepository;
        _uow = uow;
    }

    public async Task<Result<Guid>> Handle(UpdateChatCommand request, CancellationToken cancellationToken)
    {
        var chat = await _chatRepository.GetByIdAsync(request.ChatId, cancellationToken);
        if (chat == null || !chat.Members.Any(m => m.UserId == request.UserId))
        {
            return Result.Failure<Guid>(ChatErrors.ChatNotFound);
        }

        if (request.Name != null)
        {
            chat.UpdateName(request.Name);
        }

        if (request.Description != null)
        {
            chat.UpdateDescription(request.Description);
        }

        _chatRepository.Update(chat);
        await _uow.SaveChangesAsync(cancellationToken);

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

