"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authCommand = authCommand;
const chalk_1 = __importDefault(require("chalk"));
const dedent_1 = __importDefault(require("dedent"));
const envars_1 = require("../envars");
const fetch_1 = require("../fetch");
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 authCommand(program) {
    const authCommand = program.command('auth').description('Manage authentication');
    authCommand
        .command('login')
        .description('Login')
        .option('-o, --org <orgId>', 'The organization id to login to.')
        .option('-h,--host <host>', 'The host of the Trusys instance. This needs to be the url of the API if different from the app url.')
        .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.exitCode = 1;
            return;
        }
        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}`));
        }
        catch (err) {
            const errorMessage = err?.response?.data?.message || err.message;
            logger_1.default.error(`❌ Authentication failed: ${errorMessage}`);
            process.exitCode = 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"));
            return;
        }
        await cloud_1.cloudConfig.delete();
        // Always unset projectId on logout
        logger_1.default.info(chalk_1.default.green('✅ Successfully logged out'));
        return;
    });
    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.`);
                return;
            }
            const apiHost = cloud_1.cloudConfig.getApiHost();
            logger_1.default.info((0, dedent_1.default) `
          ${chalk_1.default.green.bold('Currently logged with:')}
          Project: ${projectId}
          App URL: ${chalk_1.default.cyan(cloud_1.cloudConfig.getAppUrl())}`);
            // logger.info(chalk.green(`API host: ${apiHost}`));
            const response = await (0, fetch_1.fetchWithProxy)(`${apiHost}/api/v1/users/me`, {
                headers: {
                    Authorization: `Bearer ${apiKey}`,
                },
            });
            if (!response.ok) {
                // throw new Error('Failed to fetch user info: ' + response.statusText);
            }
            telemetry_1.default.record('command_used', {
                name: 'auth whoami',
            });
            await telemetry_1.default.send();
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            logger_1.default.error(`Failed to get user info: ${errorMessage}`);
            process.exitCode = 1;
        }
    });
}
//# sourceMappingURL=auth.js.map