'use strict';

const dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');

dayjs.extend(relativeTime);

const FS = require('../models/FS');
const User = require('../models/User');
const Org = require('../models/Org');
const API = require('../models/API');
const Service = require('../models/Service');

module.exports = async (config, cli) => {
  const fs = new FS();
  const user = new User();

  cli.logLogo();
  cli.sessionStart('loading', { timer: false });

  if ((await fs.isCwdEmpty()) || !(await fs.isProjectDirectory())) {
    throw new Error('package.json not found in the cwd');
  }

  const org = new Org({ user });
  await org.authorize();

  const api = new API({ org });
  const service = new Service({ api, org }); // todo pass projectFile.name

  const instances = (await service.listInstances()).sort(
    (olderInstance, newerInstance) => newerInstance.updatedAt - olderInstance.updatedAt
  );

  // const createdAt = dayjs(instances[0].createdAt).format('DD/MM/YYYY');
  // console.log(createdAt);

  const serviceName = service.serviceName;
  const numberOfInstances = String(instances.length);

  cli.log();
  cli.log(
    cli.styles.none(
      `the ${cli.styles.bold(serviceName)} service has ${cli.styles.bold(
        numberOfInstances
      )} instances:`
    )
  );
  cli.log();

  // todo handle zero instances in the CLI
  for (const instance of instances) {
    const updatedAt = dayjs(instance.updatedAt).fromNow();
    cli.log();
    cli.log(
      cli.styles.none(
        `the ${cli.styles.bold(instance.instanceName)} instance was updated ${cli.styles.bold(
          updatedAt
        )}`
      )
    );
    cli.logUrl(instance.url);
  }

  cli.log();
  cli.log();
  cli.log(`${cli.styles.dim('see more →')} https://cloud.serverless.com/wip`);

  cli.sessionStop('done');
};
