'use strict';

/*
 * Serverless Components: CLI Handler
 */

const minimist = require('minimist');
const CLI = require('./CLI');

module.exports = async () => {
  const args = minimist(process.argv.slice(2));

  const params = [];
  if (args._[1]) {
    params.push(args._[1]);
  }
  if (args._[2]) {
    params.push(args._[2]);
  }
  if (args._[3]) {
    params.push(args._[3]);
  }
  if (args._[4]) {
    params.push(args._[4]);
  }

  const config = { ...args, params };
  if (config._) {
    delete config._;
  }

  process.env.SERVERLESS_PLATFORM_STAGE = 'dev';
  // config.platformStage = process.env.SERVERLESS_PLATFORM_STAGE || 'prod';
  config.debug = process.env.SLS_DEBUG || !!args.debug;

  // Add stage environment variable
  if (args.stage && !process.env.SERVERLESS_STAGE) {
    process.env.SERVERLESS_STAGE = args.stage;
  }

  // Initialize CLI utilities
  const cli = new CLI(config);

  const commands = require('./commands');

  let command = args._[0];

  if (args.help || args.h) {
    command = 'help';
  }

  if (args.version || args.v) {
    command = 'version';
  }

  config.command = command;

  try {
    if (!commands[command]) {
      throw new Error(
        `command "${command}" is not a valid command. Please see the docs for a complete list of valid commands.`
      );
    }
    await commands[command](config, cli);
  } catch (error) {
    process.exitCode = 1;

    if (cli.isSessionActive()) {
      cli.sessionStop(error, 'error');
    } else {
      cli.logError(error);
      cli.log();
    }
  }

  return null;
};
