const config = require('config');
const Promise = require('bluebird');
const uuid = require('node-uuid');

module.exports = app => {
  const services = {
    paypal: (group, expense, email, preapprovalKey) => {
      const uri = `/groups/${group.id}/expenses/${expense.id}/paykey/`;
      const baseUrl = config.host.webapp + uri;
      const amount = expense.amount/100;
      const payload = {
        requestEnvelope: {
          errorLanguage: 'en_US',
          detailLevel: 'ReturnAll'
        },
        actionType: 'PAY',
        // TODO does PayPal accept all the currencies that we support in our expenses?
        currencyCode: expense.currency,
        feesPayer: 'SENDER',
        memo: `Reimbursement from ${group.name}: ${expense.description}`,
        trackingId: [uuid.v1().substr(0, 8), expense.id].join(':'),
        preapprovalKey,
        returnUrl: `${baseUrl}/success`,
        cancelUrl: `${baseUrl}/cancel`,
        receiverList: {
          receiver: [
            {
              email,
              amount,
              paymentType: 'SERVICE'
            }
          ]
        }
      };

      return new Promise((resolve, reject) => {
        app.paypalAdaptive.pay(payload, (err, res) => {
          if (err) {
            console.log("PayPal payment error", err, res);
            return reject(new Error(res.error[0].message));
          }
          resolve(res);
        });
      });
    }
  };

  return service => {
    const s = services[service];
    if (!s) {
      throw new errors.NotImplemented('This service is not implemented yet for payment.');
    }
    return s;
  };
};

@@ -1286,21 +1286,328 @@
 rror
+: 
 %22, err
-, res);
+);%0A            console.log(%22PayPal response: %22, res);%0A            if (res.error && res.error%5B0%5D && res.error%5B0%5D.parameter) %7B%0A              console.log(%22PayPal error.parameter: %22, res.error%5B0%5D.parameter); // this'll give us more details on the error%0A            %7D%0A            console.log(%22PayPal payment error: %22)
 %0A   

add more info to debug paypal (#508)