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

namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.DeleteBlogPostImage;

public class DeleteBlogPostImageCommandHandler : IRequestHandler<DeleteBlogPostImageCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteBlogPostImageCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.BlogPostImages.FindAsync(new object[] { request.Id }, cancellationToken);
        if (entity == null || entity.IsDeleted)
            throw new NotFoundException(nameof(BlogPostImage), request.Id);

        entity.IsDeleted = true;

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
