using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserRoleCQ.Commands.UpdateUserRole;
public class UpdateUserRoleCommandHandler : IRequestHandler<UpdateUserRoleCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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