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

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

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

internal sealed class AddToFolderCommandHandler : ICommandHandler<AddToFolderCommand>
{
    private readonly IUserChatSettingsRepository _settingsRepository;
    private readonly IChatsUnitOfWork _unitOfWork;
    private readonly IChatsSettings _chatsSettings;

    public AddToFolderCommandHandler(
        IUserChatSettingsRepository settingsRepository, 
        IChatsUnitOfWork unitOfWork,
        IChatsSettings chatsSettings)
    {
        _settingsRepository = settingsRepository;
        _unitOfWork = unitOfWork;
        _chatsSettings = chatsSettings;
    }

    public async Task<Result> Handle(AddToFolderCommand request, CancellationToken cancellationToken)
    {
        if (!_chatsSettings.Current.EnableFolders)
        {
            return Result.Failure(ChatErrors.FoldersDisabled);
        }

        var settings = await _settingsRepository.GetAsync(request.UserId, request.ChatId, cancellationToken);
        
        if (settings == null)
        {
            settings = UserChatSettings.Create(request.UserId, request.ChatId);
            _settingsRepository.Add(settings);
        }

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

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