using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserRoleCQ.Commands.DeleteUserRole;
public class DeleteUserRoleCommandHandler : IRequestHandler<DeleteUserRoleCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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