using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductTagCQ.Commands.UpdateProductTag;
public class UpdateProductTagCommandHandler : IRequestHandler<UpdateProductTagCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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

