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






using Knot.Modules.Stories.Application.DTOs;



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

public record DeleteStoryCommand(Guid UserId, Guid StoryId) : ICommand<MessageResponse>;

internal sealed class DeleteStoryCommandHandler : ICommandHandler<DeleteStoryCommand, MessageResponse>
{
    private readonly Knot.Modules.Stories.Application.Abstractions.IStoryRepository _repository;

    public DeleteStoryCommandHandler(Knot.Modules.Stories.Application.Abstractions.IStoryRepository repository)
    {
        _repository = repository;
    }

    public async Task<Result<MessageResponse>> Handle(DeleteStoryCommand request, CancellationToken cancellationToken)
    {
        var story = await _repository.GetByIdAsync(request.StoryId, cancellationToken);
        if (story == null)
        {
            return Result.Failure<MessageResponse>(StoryErrors.StoryNotFound);
        }
        if (story.UserId != request.UserId)
        {
            return Result.Failure<MessageResponse>(StoryErrors.Unauthorized);
        }

        await _repository.DeleteAsync(story, cancellationToken);

        return Result.Success(new MessageResponse("Story deleted"));
    }
}




