@Override
  public Mono<RemoveDeviceResponse> removeDevice(final RemoveDeviceRequest request) {
    if (request.getId() == Device.PRIMARY_ID) {
      throw Status.INVALID_ARGUMENT.withDescription("Cannot remove primary device").asRuntimeException();
    }

    final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();

    if (authenticatedDevice.deviceId() != Device.PRIMARY_ID && request.getId() != authenticatedDevice.deviceId()) {
      throw Status.PERMISSION_DENIED
          .withDescription("Linked devices cannot remove devices other than themselves")
          .asRuntimeException();
    }

    final byte deviceId = DeviceIdUtil.validate(request.getId());

    return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
        .map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
        .flatMap(account -> Mono.fromFuture(accountsManager.removeDevice(account, deviceId)))
        .thenReturn(RemoveDeviceResponse.newBuilder().build());
  }
@Test
  void removeDeviceNonPrimaryMatchAuthenticated() {
    final byte deviceId = Device.PRIMARY_ID + 1;

    mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);

    final RemoveDeviceResponse ignored = authenticatedServiceStub().removeDevice(RemoveDeviceRequest.newBuilder()
        .setId(deviceId)
        .build());

    verify(accountsManager).removeDevice(authenticatedAccount, deviceId);
  }