using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;

public class AddBlogPostImageCommandHandler : IRequestHandler<AddBlogPostImageCommand, long>
{
    private readonly IApplicationDbContext _context;

    public AddBlogPostImageCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<long> Handle(AddBlogPostImageCommand request, CancellationToken cancellationToken)
    {
        var blogPost = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.BlogPostId && !x.IsDeleted, cancellationToken);
        if (blogPost == null)
            throw new NotFoundException(nameof(BlogPost), request.BlogPostId);

        var entity = new BlogPostImage
        {
            BlogPostId = request.BlogPostId,
            ImagePath = request.ImagePath,
            ThumbnailPath = request.ThumbnailPath,
            AltText = request.AltText,
            Caption = request.Caption,
            SortOrder = request.SortOrder
        };

        _context.BlogPostImages.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return entity.Id;
    }
}
