"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.trusysAuthCommand = trusysAuthCommand;
const chalk_1 = __importDefault(require("chalk"));
const dedent_1 = __importDefault(require("dedent"));
const envars_1 = require("../envars");
const accounts_1 = require("../globalConfig/accounts");
const cloud_1 = require("../globalConfig/cloud");
const logger_1 = __importDefault(require("../logger"));
const telemetry_1 = __importDefault(require("../telemetry"));
const verifyApiKey_1 = require("../util/verifyApiKey");
function trusysAuthCommand(program) {
    const authCommand = program.command('auth').description('Manage authentication');
    authCommand
        .command('login')
        .description('Login')
        .option('-k, --api-key <apiKey>', 'Login using an API key.')
        .action(async (cmdObj) => {
        // Prefer CLI arg, then env var
        const apiKey = cmdObj.apiKey || (0, envars_1.getEnvString)('TRUSYS_API_KEY');
        telemetry_1.default.record('command_used', {
            name: 'auth login',
        });
        await telemetry_1.default.send();
        if (!apiKey) {
            logger_1.default.error('❌ Please provide an API key using -k or --api-key or set TRUSYS_API_KEY in your environment');
            process.exit(1);
        }
        const cpApiHost = cloud_1.cloudConfig.getCpApiHost();
        // logger.info(chalk.green(`CP API host: ${cpApiHost}`));
        try {
            // 🧠 Custom API key validation call
            const response = await (0, verifyApiKey_1.verifyApiKey)(apiKey, cpApiHost);
            // logger.info(chalk.green(`VALIDATION RESPONSE: ${JSON.stringify(response)}`));
            const projectId = response?.result?.apiKeyData?.project_id;
            const workSpaceId = response?.result?.apiKeyData?.org_id;
            if (!projectId) {
                throw new Error('No projectId returned from API');
            }
            cloud_1.cloudConfig.setApiKey(apiKey);
            (0, accounts_1.setProjectId)(projectId);
            (0, accounts_1.setWorkSpaceId)(workSpaceId);
            logger_1.default.info(chalk_1.default.green(`✅ Successfully logged in with projectId: ${projectId}`));
            process.exit(0);
        }
        catch (err) {
            const errorMessage = err?.response?.data?.message || err.message;
            logger_1.default.error(`❌ Authentication failed: ${errorMessage}`);
            process.exit(1);
        }
    });
    authCommand
        .command('logout')
        .description('Logout')
        .action(async () => {
        const projectId = (0, accounts_1.getProjectId)();
        const apiKey = cloud_1.cloudConfig.getApiKey() || (0, envars_1.getEnvString)('TRUSYS_API_KEY');
        if (!projectId && !apiKey) {
            logger_1.default.info(chalk_1.default.yellow("You're already logged out - no active session to terminate"));
            process.exit(0);
        }
        await cloud_1.cloudConfig.delete();
        // Always unset projectId on logout
        logger_1.default.info(chalk_1.default.green('✅ Successfully logged out'));
        process.exit(0);
    });
    authCommand
        .command('whoami')
        .description('Show current user information')
        .action(async () => {
        try {
            const projectId = (0, accounts_1.getProjectId)();
            const apiKey = cloud_1.cloudConfig.getApiKey();
            if (!projectId || !apiKey) {
                await cloud_1.cloudConfig.delete();
                logger_1.default.info(`Not logged in. Run ${chalk_1.default.bold('trusys auth login')} to login.`);
                process.exit(0);
            }
            logger_1.default.info((0, dedent_1.default) `
          ${chalk_1.default.green.bold('Currently logged with:')} Project: ${projectId}`);
            telemetry_1.default.record('command_used', {
                name: 'auth whoami',
            });
            await telemetry_1.default.send();
            process.exit(0);
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            logger_1.default.error(`Failed to get login info: ${errorMessage}`);
            process.exit(1);
        }
    });
}
//# sourceMappingURL=trusys_auth.js.map