using Knot.Contracts.Conversations.Domain;
using Knot.Contracts.Conversations.Application.Abstractions;
using Knot.Shared.Kernel;
using MediatR;

namespace Knot.Modules.Conversations.Application.Folders.Commands.RemoveFromFolder;

public record RemoveFromFolderCommand(Guid UserId, Guid ChatId, List<Guid> FolderIds) : ICommand;

internal sealed class RemoveFromFolderCommandHandler : ICommandHandler<RemoveFromFolderCommand>
{
    private readonly IUserChatSettingsRepository _settingsRepository;
    private readonly IChatsUnitOfWork _unitOfWork;

    public RemoveFromFolderCommandHandler(IUserChatSettingsRepository settingsRepository, IChatsUnitOfWork unitOfWork)
    {
        _settingsRepository = settingsRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result> Handle(RemoveFromFolderCommand request, CancellationToken cancellationToken)
    {
        var settings = await _settingsRepository.GetAsync(request.UserId, request.ChatId, cancellationToken);
        
        if (settings == null)
        {
            return Result.Success();
        }

        foreach (var folderId in request.FolderIds)
        {
            settings.RemoveFromFolder(folderId);
        }

        _settingsRepository.Update(settings);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
        return Result.Success();
    }
}
