import { CliTerseError } from '@alwaysai/alwayscli';
import * as logSymbols from 'log-symbols';

import { alwaysaiUserLoginPromptComponent } from './alwaysai-user-login-prompt-component';
import { ALWAYSAI_CLI_EXECUTABLE_NAME } from '../../constants';
import { echo } from '../../util';
import { CliAuthenticationClient, getBaseURL } from '../../infrastructure';

const YOU_MUST_BE_LOGGED_IN = 'You must be logged in to run this command.';
const REGISTER_ACCOUNT =
  'Need a free alwaysAI account? Hold CTRL/CMD and click here to get started';

export async function checkUserIsLoggedInComponent(props: { yes: boolean }) {
  const { yes } = props;
  if (!CliAuthenticationClient().isSignedIn()) {
    if (yes) {
      throw new CliTerseError(
        `${YOU_MUST_BE_LOGGED_IN} Please either re-run this command without the "yes" flag, or run "${ALWAYSAI_CLI_EXECUTABLE_NAME} user login" and try again.`
      );
    } else {
      echo(`${logSymbols.warning} ${YOU_MUST_BE_LOGGED_IN}`);
      echo(`${logSymbols.info} ${REGISTER_ACCOUNT}: ${getBaseURL()}/register`);
      await alwaysaiUserLoginPromptComponent();
    }
  }
}
