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

namespace Knot.Modules.Stories.Application.Stories.Queries.GetStoryReplies;

public record GetStoryRepliesQuery(Guid UserId, Guid StoryId) : IQuery<List<StoryReplyDto>>;

internal sealed class GetStoryRepliesQueryHandler : IQueryHandler<GetStoryRepliesQuery, List<StoryReplyDto>>
{
    private readonly IStoryRepository _storyRepository;

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

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

        var replies = story.Replies.ConvertAll(r => new StoryReplyDto(
            r.Id,
            r.UserId,
            r.Username,
            r.DisplayName,
            r.Avatar,
            r.Content,
            r.CreatedAt
        ));

        return Result.Success(replies);
    }
}
