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.AddStoryReply;

public record AddStoryReplyCommand(Guid UserId, Guid StoryId, string Content) : ICommand<bool>;

internal sealed class AddStoryReplyCommandHandler : ICommandHandler<AddStoryReplyCommand, bool>
{
    private readonly IStoryRepository _storyRepository;

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

    public async Task<Result<bool>> Handle(AddStoryReplyCommand 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.AddReply(request.UserId, request.Content);
        await _storyRepository.UpdateAsync(story, cancellationToken);

        return Result.Success(true);
    }
}
