var request = require('request-promise-native');

exports.handler = (event, context, callback) => {
  console.log("\nENV: \n" + JSON.stringify(process.env) + "\n\n");
  console.log("\nEvent: \n" + JSON.stringify(event) + "\n\n");
  console.log("\nContext: \n" + JSON.stringify(context) + "\n\n");

  var code = event.queryStringParameters.code;
  promiseToGetAuthorizationToken(code).then(
    promiseToSaveAuthorization, 
    handleSlackError
  );
  
  callback(null, { body: "Hi! From the API." });
};

var promiseToGetAuthorizationToken = function(code, options={}){
  return request({
    url: 'https://slack.com/api/oauth.access',
    method: 'POST',
    form: {
      client_id: (options.client_id || process.env.CLIENT_ID),
      client_secret: (options.client_secret || process.env.CLIENT_SECRET),
      code: code
    }
  });
};

var handleSlackError = function(failure){
  console.log("BOO");
  console.log(failure);
};

var promiseToSaveAuthorization = function(response){
  console.log("YAY");
  console.log(response);
};

//request({url: "https://www.npr.org"}).then((yay)=>{ console.log("YAY"); console.log(yay)}, (boo)=>{ console.log("BOO"); console.log(boo)})

/*

slack_authorizations:
  created_at, DateTime
  details, JSONB
  verified, Boolean
  verified_by, ???
  verified_at, DateTime

admins:
  id, Serial
  name, Varchar(255)
  created_at, DateTime
*/
@@ -1032,150 +1032,8 @@
 %7D;%0A%0A
-//request(%7Burl: %22https://www.npr.org%22%7D).then((yay)=%3E%7B console.log(%22YAY%22); console.log(yay)%7D, (boo)=%3E%7B console.log(%22BOO%22); console.log(boo)%7D)%0A%0A
 /*%0A%0A

Remove debug note