const qs = require('querystring');
const responder = require('./util/responder');
const auth = require('./util/auth');
const controllers = require('../controllers');
const keepAlive = require('./util/keepAlive');

const parseBody = event => {
  const contentType = event.headers['Content-Type'];
  if (event.body) {
    if (contentType.startsWith('application/x-www-form-urlencoded')) {
      return qs.parse(event.body);
    }
    if (contentType.startsWith('application/json')) {
      return JSON.parse(event.body);
    }
  }
  return {};
};

const handler = (event, context, callback) => {
  const body = parseBody(event);
  const query = event.queryStringParameters || {};

  const code = body.code || query.code;
  const state = body.state || query.state;

  const redirectUri = `https://${event.headers.Host}/${
    event.requestContext.stage
  }/callback`;

  controllers(responder(callback)).token(
    code,
    state,
    auth.getIssuer(event.headers.Host),
    redirectUri
  );
};

module.exports.handler = keepAlive(handler);
