/**
* Login command
*/
import inquirer from 'inquirer';
import chalk from 'chalk';
import { AuthManager } from '../../core/auth/AuthManager';
import { createSessionStore } from '../utils/session';
import { printSuccess, printError, printInfo } from '../utils/formatters';
interface LoginOptions {
email?: string;
password?: string;
url?: string;
}
/**
* Login command handler
*/
export async function loginCommand(options: LoginOptions): Promise<void> {
try {
printInfo('WhaTap MXQL CLI - Login');
console.log('');
// Get credentials
let { email, password, url } = options;
// Prompt for missing credentials
if (!email || !password || !url) {
console.log(chalk.gray('Enter your WhaTap credentials:'));
console.log('');
const answers = await inquirer.prompt([
{
type: 'input',
name: 'email',
message: 'Email:',
when: !email,
validate: (input) => {
if (!input || !input.includes('@')) {
return 'Please enter a valid email address';
}
return true;
},
},
{
type: 'password',
name: 'password',
message: 'Password:',
when: !password,
validate: (input) => {
if (!input) {
return 'Password is required';
}
return true;
},
},
{
type: 'input',
name: 'url',
message: 'Service URL:',
default: 'https://service.whatap.io',
when: !url,
validate: (input) => {
if (!input || !input.startsWith('http')) {
return 'Please enter a valid URL';
}
return true;
},
},
]);
email = email || answers.email;
password = password || answers.password;
url = url || answers.url;
}
// Login
console.log('');
printInfo('Authenticating...');
const sessionStore = createSessionStore();
const authManager = new AuthManager(sessionStore);
await authManager.login({
email: email!,
password: password!,
serviceUrl: url!,
});
console.log('');
printSuccess('Successfully logged in!');
console.log('');
console.log(chalk.gray(' Email:'), chalk.white(email));
console.log(chalk.gray(' Service URL:'), chalk.white(url));
console.log('');
console.log(chalk.cyan('Next steps:'));
console.log(chalk.gray(' • List projects:'), chalk.white('whatap-mxql projects'));
console.log(chalk.gray(' • Execute query:'), chalk.white('whatap-mxql query <pcode> "<mxql>"'));
console.log(chalk.gray(' • Interactive mode:'), chalk.white('whatap-mxql interactive'));
console.log('');
} catch (error: any) {
console.log('');
printError('Login failed', error);
if (error.message.includes('401') || error.message.includes('Unauthorized')) {
console.log('');
console.log(chalk.yellow('Hint: Please check your email and password'));
} else if (error.message.includes('ENOTFOUND') || error.message.includes('ECONNREFUSED')) {
console.log('');
console.log(chalk.yellow('Hint: Please check your network connection and service URL'));
}
process.exit(1);
}
}