using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogPostCQ.Commands.IncrementViewCount;

public class IncrementViewCountCommandHandler : IRequestHandler<IncrementViewCountCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(IncrementViewCountCommand request, CancellationToken cancellationToken)
    {
        var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
        if (post != null)
        {
            post.ViewCount++;
            await _context.SaveChangesAsync(cancellationToken);
        }

        return Unit.Value;
    }
}
