using Femto.Modules.Blog.Application.Queries.GetPosts.Dto;
using Femto.Modules.Blog.Domain.Posts;
using MediatR;

namespace Femto.Modules.Blog.Application.Commands.CreatePost;

internal class CreatePostCommandHandler(BlogContext context)
    : IRequestHandler<CreatePostCommand, PostDto>
{
    public async Task<PostDto> Handle(
        CreatePostCommand request,
        CancellationToken cancellationToken
    )
    {
        var post = new Post(
            request.AuthorId,
            request.Content,
            request
                .Media.Select(media => new PostMedia(
                    media.MediaId,
                    media.Url,
                    media.Type,
                    media.Order,
                    media.Width,
                    media.Height
                ))
                .ToList(),
            request.IsPublic is true
        );

        await context.AddAsync(post, cancellationToken);

        return new PostDto(
            post.Id,
            post.Content,
            post.Media.Select(m => new PostMediaDto(m.Url, m.Width, m.Height)).ToList(),
            post.PostedOn,
            new PostAuthorDto(post.AuthorId, request.CurrentUser.Username),
            [],
            post.PossibleReactions,
            []
        );
    }
}
