using System;
using System.Threading;
using System.Threading.Tasks;
using Knot.Modules.Stories.Application.Abstractions;
using Knot.Shared.Kernel;

namespace Knot.Modules.Stories.Application.Stories.Commands.RemoveStoryReaction;

public record RemoveStoryReactionCommand(Guid UserId, Guid StoryId, string Emoji) : ICommand<bool>;

internal sealed class RemoveStoryReactionCommandHandler : ICommandHandler<RemoveStoryReactionCommand, bool>
{
    private readonly IStoryRepository _storyRepository;

    public RemoveStoryReactionCommandHandler(IStoryRepository storyRepository)
    {
        _storyRepository = storyRepository;
    }

    public async Task<Result<bool>> Handle(RemoveStoryReactionCommand request, CancellationToken cancellationToken)
    {
        var story = await _storyRepository.GetByIdAsync(request.StoryId, cancellationToken);
        if (story == null)
        {
            return Result.Failure<bool>(new Error("Stories.NotFound", "Story not found."));
        }

        story.RemoveReaction(request.UserId, request.Emoji);
        await _storyRepository.UpdateAsync(story, cancellationToken);

        return Result.Success(true);
    }
}
