using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductCategoryCQ.Commands.UpdateProductCategory;
public class UpdateProductCategoryCommandHandler : IRequestHandler<UpdateProductCategoryCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(UpdateProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.ProductCategories
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(ProductCategory), request.Id);
        request.Adapt(entity);
        _context.ProductCategories.Update(entity);
        entity.AddDomainEvent(new UpdateProductCategoryEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
