"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = validateSaveUdacityAuthToken;

var _ora = _interopRequireDefault(require("ora"));

var _utils = require("../utils");

var _api = require("../../api");

var _config = require("../../config");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Validate a token by sending request to Udacity API and save it
 * if it is valid
 * @param {string} token Udacity authentication token
 */
async function validateSaveUdacityAuthToken(token) {
  const spinner = (0, _ora.default)('Validate Udacity authentication token via Udacity API').start();

  try {
    const res = await (0, _api.fetchUdacityUserInfo)(token);

    if (!res.data || !res.data.user) {
      spinner.fail();

      _utils.logger.error(`Could not validate your Udacity token. Please try again. Here's the error message:
      ${res.body}`);

      return null;
    } // save token


    _utils.config.set(_config.CLI_CONFIG_UDACITY_AUTH_TOKEN, token);

    spinner.succeed();
    const {
      user
    } = res.data;
    const name = user.nickname || user.first_name;
    const msgSuccess = 'You have successfully saved authentication token locally!';

    if (name) {
      _utils.logger.info(`Hi ${name}. ${msgSuccess}`);
    } else {
      _utils.logger.info(`${msgSuccess}`);
    }

    return token;
  } catch (error) {
    spinner.fail();

    _utils.logger.error(`Failed to validate your Udacity token. Please try again. Here's the error message:
${JSON.stringify(error, null, 4)}`);

    return null;
  }
}