const _ = require('lodash');

const intBase = 10;

/** Get routes

  {
    destination: <Send Destination Hex Encoded Public Key String>
    lnd_grpc_api: <Object>
    tokens: <Tokens to Send Number>
  }

  @returns via cbk
  {
    routes: [{
      fee: <Route Fee Tokens Number>
    }]
  }
*/
module.exports = (args, cbk) => {
  if (!args.lnd_grpc_api) {
    return cbk([500, 'Missing lnd grpc api', args]);
  }

  if (!args.destination || !args.tokens) {
    return cbk([500, 'Expected destination, tokens', args]);
  }

  return args.lnd_grpc_api.queryRoutes({
    amt: args.tokens,
    pub_key: args.destination,
  },
  (err, res) => {
    if (!!err) {
      return cbk(err);
    }

    if (!res || !Array.isArray(res.routes)) {
      return cbk([500, 'Expected routes', res]);
    }

    const invalidRoutes = res.routes
      .map((route) => parseInt(route.total_fees, intBase))
      .filter((fees) => !_.isFinite(fees));

    if (!!invalidRoutes.length) {
      return cbk([500, 'Expected valid routes']);
    }

    const routes = res.routes.map((route) => {
      return {fee: parseInt(route.total_fees, intBase)};
    });

    return cbk(null, {routes});
  });
};


@@ -44,16 +44,155 @@
  = 10;%0A%0A
+const pathNotFoundErrors = %5B%0A  'noPathFound',%0A  'noRouteFound',%0A  'insufficientCapacity',%0A  'maxHopsExceeded',%0A  'targetNotInNetwork',%0A%5D;%0A%0A
 /** Get 
@@ -780,41 +780,273 @@
     
-if (!!err) %7B%0A      return cbk(err
+// Exit early when an error indicates that no routes are possible%0A    if (!!err && _.isFinite(err.code) && !!pathNotFoundErrors%5Berr.code%5D) %7B%0A      return cbk(null, %7Broutes: %5B%5D%7D);%0A    %7D%0A%0A    if (!!err) %7B%0A      return cbk(%5B500, 'Unexpected error getting routes', err%5D
 );%0A 

handle path not found errors in route lookup