"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TenantContextualizer = void 0;
const tslib_1 = require("tslib");
const auth_entities_1 = require("@codiac.io/codiac-common/security/auth-entities");
const utilities_1 = require("@codiac.io/codiac-common/utilities");
const codiac_relay_contracts_1 = require("@codiac.io/codiac-relay-contracts");
const ops_1 = require("../ops");
const user_context_loader_1 = require("../user-context-loader");
const stringify = require("json-stringify-safe");
const _ = require("lodash");
/** Interfaces with CLI user to establish a tenant context.  */
class TenantContextualizer {
    /**
     * @param projCfg The In-memory representation of the project's thaulconfig file.
     */
    constructor(cliEnviro, projCfg, authClient, _projCfgRepo, ui, styler, logger) {
        this.cliEnviro = cliEnviro;
        this.projCfg = projCfg;
        this.authClient = authClient;
        this._projCfgRepo = _projCfgRepo;
        this.ui = ui;
        this.styler = styler;
        this.logger = logger;
        this.userContextLoader = new user_context_loader_1.UserContextLoader(this.cliEnviro, logger);
        this.userContextRepo = new user_context_loader_1.UserContextManager(this.cliEnviro, authClient, logger);
    }
    /** Ensures that a valid tenant is assigned
     * and the user has a valid tenant contributor token.
     *
     * @param currentContext The Machine-user context.  It's just the starting point, not necessarily the right one.  ie: Project config enforcement may switch it on you.
    */
    establishTenantContext(currentContext) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    // Step -1) Enforce the proect tenant c.  Proj config should govern. If we are in a project, and there's no tenant code, then remain anonymous.?
                    /** This tenant code MUST BE ENFORCED. */
                    let requiredTenantCode;
                    /** This tenant code is NOT enforced. */
                    let suggestedTenantCode;
                    if (this.projCfg && this._projCfgRepo) {
                        // ----------------------------
                        // WITHIN A PROJECT FOLDER
                        // If there's a project tenant code set, then we HAVE TO ENFORCE IT.
                        // Otherwise the interaction can end up with whatever tenant code is convenient or selected.
                        if (this.projCfg.tenantCode !== undefined
                            && this.projCfg.tenantCode !== ""
                            && this.projCfg.tenantCode != ops_1.DxConstants.UNREGISTERED_TENANT_CODE) {
                            requiredTenantCode = this.projCfg.tenantCode;
                        }
                        // ----------------------------
                    }
                    else {
                        // ----------------------------
                        // ENTERPRISE-ONLY OR PRE-INIT: OUTSIDE OF PROJECT FOLDER
                        // Nothing to fall back on here, this var is only a suggestion, 
                        // and there may be no requirement. 
                        // The user interactions below will reconcile an anonymous user. 
                        suggestedTenantCode = currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentTenantCode;
                        // ----------------------------
                    }
                    /** Defaults to anonymous */
                    let loadedUser;
                    if (requiredTenantCode !== null && requiredTenantCode !== void 0 ? requiredTenantCode : suggestedTenantCode) {
                        // There are 5 cases we need to support:
                        // 1) Cached user's current tenant code is a match
                        // 2) Cached user has a match in its other profiles
                        // 3) Cached user has no match, but it has one online (ie: cache is stale)
                        // 4) Cached user has no matches anywhere.
                        // 5) There is no cached user.
                        // This loaded user is either a match, it's a principal, or its undefined.
                        loadedUser = yield this.tryMatchGivenOrCached((requiredTenantCode !== null && requiredTenantCode !== void 0 ? requiredTenantCode : suggestedTenantCode), currentContext);
                    }
                    else {
                        loadedUser = currentContext; // there's no requirements, we may as well use what we've got.
                    }
                    // ---ORIGINAL-------------------------
                    // // STEP a:  Load any locally cached user and tenant profiles
                    // /** Defaults to anonymous */
                    // let cachedUserContext = currentContext ?? this.userContextLoader.loadUserContext(this.projCfg.tenantCode);
                    // this.logger.trace(`After loadUserContext(${this.projCfg.tenantCode})`);
                    // // STEP b: Gather up whatever we have stored for user and tenant tokens
                    // let projTenantCode = (this.projCfg.tenantCode && this.projCfg.tenantCode != DxConstants.UNREGISTERED_TENANT_CODE) ? this.projCfg.tenantCode : undefined;
                    // this.logger.trace(`Project tenantCode: ${projTenantCode}`);
                    // ----------------------------
                    let ultimateUserContext;
                    if (loadedUser && (requiredTenantCode !== null && requiredTenantCode !== void 0 ? requiredTenantCode : suggestedTenantCode)) {
                        ultimateUserContext = ultimateUserContext !== null && ultimateUserContext !== void 0 ? ultimateUserContext : this.tryUseCurrentToken(loadedUser, (requiredTenantCode !== null && requiredTenantCode !== void 0 ? requiredTenantCode : suggestedTenantCode));
                        // this.logger.trace(`Ultimate UserContext after tryUseCurrentToken: `, ultimateUserContext);
                        ultimateUserContext = ultimateUserContext !== null && ultimateUserContext !== void 0 ? ultimateUserContext : yield this.trySwitchTenant(loadedUser, (requiredTenantCode !== null && requiredTenantCode !== void 0 ? requiredTenantCode : suggestedTenantCode));
                    }
                    // this.logger.trace(`Cached UserContext before user interaction: `, loadedUser);
                    // this.logger.trace(`Ultimate UserContext before user interaction: `, ultimateUserContext);
                    // Methods below call out for user input.
                    if (requiredTenantCode) {
                        // ENFORCE IT. This will block the command if they cant authenticate.
                        ultimateUserContext = ultimateUserContext !== null && ultimateUserContext !== void 0 ? ultimateUserContext : yield this.tryAuthenticateUnderTenant(requiredTenantCode, loadedUser === null || loadedUser === void 0 ? void 0 : loadedUser.userName);
                        // } else if (suggestedTenantCode) {
                        //   // User was logged in but either has an expired token (most likely) or is no longer part of the suggested tenant
                        //   // User should be prompted to login again, but given the option to switch tenants, using suggestedTenantCode as a default.
                        //   ultimateUserContext = ultimateUserContext ?? await this.tryAuthenticateUnderTenant(suggestedTenantCode, loadedUser?.userName);
                    }
                    else { // this is an "else" because we are not going to allow this command to change the project tenant assignment (only add one if it hasnt been assigned).
                        ultimateUserContext = ultimateUserContext !== null && ultimateUserContext !== void 0 ? ultimateUserContext : yield this.trySelectFromMyTenants(loadedUser);
                        ultimateUserContext = ultimateUserContext !== null && ultimateUserContext !== void 0 ? ultimateUserContext : yield this.tryRegisterNewTenant(loadedUser);
                    }
                    resolve(ultimateUserContext);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    // ==========================================================================
    //                   PRIVATE SUPPORTING METHODS
    // ==========================================================================
    /** Checks the given user context and then the machine user configuration for a user profile with the given tenant.
     *
     * Returns a principal user context (undefined currentTenantCode properties) if it doesnt have a matching tenant profile.
     * Returns `undefined` if no context found at all.
     *
     * DOES NOT throw encountered exceptions, so that a login prompt can follow in case something is corrupted.
     *
     * DOES NOT validate or authenticate - merely loads whatever is the local cache.
     */
    tryMatchGivenOrCached(tenantCode, currentContext) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let found;
            try {
                // either the current context is a match,
                if ((currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentTenantCode) === tenantCode) {
                    found = currentContext; // current state A-OK.
                }
                else if (currentContext) {
                    this.userContextLoader.trySetCurrentProfileFor(tenantCode, currentContext); // We might have a cached profile for this tenant...
                    found = currentContext; // its either matching or a principal user context without a matching profile onboard (could be stale tho).
                }
                else {
                    found = this.userContextLoader.loadUserContext(tenantCode);
                }
            }
            catch (err) {
                this.logger.debug(`Error searching for cached user under tenant code: ${tenantCode}: ${(_a = err.name) !== null && _a !== void 0 ? _a : ""} ${(_b = err.message) !== null && _b !== void 0 ? _b : ""}`, stringify(err));
            }
            finally {
                return found;
            }
        });
    }
    /** Returns a valid tenant context if the given tenant is already current on the given context and the token isnt expired. */
    tryUseCurrentToken(currentContext, tenantCode) {
        if (currentContext.userName != codiac_relay_contracts_1.UserContext.ANONYMOUS_USERNAME
            && currentContext.currentTenantCode == tenantCode
            && currentContext.currentToken
            && currentContext.tokenExpiration
            && (0, utilities_1.isFuture)(currentContext.tokenExpiration)) {
            return currentContext;
        }
        else {
            return undefined;
        }
    }
    /** Attempts to switch the userContext to a locally cached profile for the given tenant,
     * and if not found, requests a switch from the auth service.
     * The current userContext will only be modified if the switch is successfully made.
     * throws is the userContext does not already contain at least one token that will identify the user (regardless of tenant).
     * SIDE-EFFECT:  This may refresh the currentToken on the current user context and cache it to the user context file. */
    trySwitchTenant(currentContext, newTenantCode) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a;
                try {
                    let ultimate;
                    if (currentContext.userName != codiac_relay_contracts_1.UserContext.ANONYMOUS_USERNAME) {
                        if (currentContext.tokens && currentContext.tokens[newTenantCode] && !this.authClient.isExpired(currentContext.tokens[newTenantCode])) { // Use the locally cached token 
                            // We already have an unexpired profile cached for this tenant.  Just make it the current one on the userContext object.
                            ultimate = currentContext;
                            ultimate.currentTenantCode = newTenantCode;
                            ultimate.currentToken = currentContext.tokens[newTenantCode];
                            ultimate.tokenExpiration = this.authClient.extractTokenExpiration(ultimate.currentToken);
                            ultimate.roles = this.authClient.extractRoles(ultimate.currentToken);
                            delete ultimate.currentEnterprise;
                            this.userContextRepo.writeUserContext(ultimate);
                            this.logger.trace(`Found an unexpired token for [${currentContext.userName}] under tenant: [${newTenantCode}].`);
                        }
                        else { // See if the remote service will let us switch
                            // Get ANY unexpired token to authenticate with 
                            // (cuz we're gonna talk to the server and have IT switch our tenant)
                            let token = (!currentContext.tokenExpiration || (0, utilities_1.isFuture)(currentContext.tokenExpiration)) ? currentContext.currentToken : undefined;
                            if (!token && currentContext.tokens) {
                                // Use one from another profile...  (any unexpired tenant token will do - we just need to identify the user)
                                for (let tc in currentContext.tokens) {
                                    if (!this.authClient.isExpired(currentContext.tokens[tc])) {
                                        token = currentContext.tokens[tc];
                                        this.logger.trace(`Found an unexpired token for [${currentContext.userName}] under tenant: [${tc}].  Using this to authenticate with the api to attempt a tenant switch.`);
                                        break;
                                    }
                                }
                            }
                            if (token) {
                                // Ask the server...
                                this.logger.trace(`Asking api to switch tenant.`);
                                this.authClient.setUserToken(token); // <-- This is brought fwd from legacy... do we need this?
                                let switchResult = yield this.authClient.Auth.SwitchTenant({ newTenantCode: newTenantCode });
                                if (switchResult.success && switchResult.output) {
                                    this._user = switchResult.output;
                                    ultimate = currentContext;
                                    ultimate.currentTenantCode = switchResult.output.tenantCode;
                                    ultimate.currentToken = this.authClient.authToken;
                                    ultimate.tokenExpiration = (ultimate.currentToken) ? this.authClient.extractTokenExpiration(ultimate.currentToken) : undefined;
                                    ultimate.roles = (_a = switchResult.output.roles) === null || _a === void 0 ? void 0 : _a.map(r => r.name);
                                    if (ultimate.currentTenantCode) {
                                        if (ultimate.currentToken)
                                            ultimate.tokens[ultimate.currentTenantCode] = ultimate.currentToken;
                                    }
                                    delete ultimate.currentEnterprise;
                                    this.userContextRepo.writeUserContext(ultimate);
                                    this.logger.trace(`Successfully Switched user context to tenant [${ultimate.currentTenantCode}] via api.`);
                                }
                                else if (switchResult.output) {
                                    // We got back a failure but refreshed the token we were using.
                                    if (token == currentContext.currentToken) /* ie: if we used the token from the original context */ {
                                        this._user = switchResult.output;
                                        currentContext.currentToken = this.authClient.authToken; // is currentContext passed in byRef?  Will this assignment be honored outside this method?
                                        currentContext.tokenExpiration = (currentContext.currentToken) ? this.authClient.extractTokenExpiration(currentContext.currentToken) : undefined;
                                    }
                                    else if (this._user) {
                                        this._user.profiles = switchResult.output.profiles; // The token was from a random tenant, so dont switch the current users tenant, just update its list of tenant profiles.
                                    }
                                    if (currentContext.currentToken)
                                        currentContext.tokens[switchResult.output.tenantCode] = currentContext.currentToken;
                                    this.userContextRepo.writeUserContext(currentContext);
                                    // We arent registered for the project tenant (http 403 ?) <--- We need to prompt for new login creds (they may want to try another user account) OR fail loudly here.
                                    this.renderNotAMember(currentContext.userName, newTenantCode);
                                }
                                else {
                                    // Our current token was invalid or expired,  (http 422 ?) <-- we need to prompt for just password. (NOTE:  That'll be server hit #2 in this sequence)
                                }
                            }
                            else {
                                // We didnt have an unexpired token to use for this.
                            }
                        }
                    }
                    resolve(ultimate);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Only diff betw this an authenticate is that
     * this method only returns a valid tenant context
     * (whereas authenticate returns a user or tenant context). */
    tryAuthenticateUnderTenant(tenantCode, defaultUserName) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let ultimate;
                    let newContext = yield this.authenticate(tenantCode, defaultUserName);
                    if (newContext) {
                        if (newContext.currentTenantCode == tenantCode) {
                            ultimate = newContext;
                        }
                        else {
                            this.renderNotAMember(newContext.userName, tenantCode);
                        }
                    }
                    resolve(ultimate);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    trySelectFromMyTenants(currentContext, allowAddNew) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let ultimate;
                    // Step 1:  GET THE USER'S LIST OF TENANTS (se we can access an updated list of profiles.
                    //          They gotta be up to date cuz access to that tenant may have been granted just seconds ago).
                    // We may need to authenticate here.  Or perhaps refresh token.  Where can we store the user from a previous server trip?  do we need to?
                    if (currentContext)
                        this.logger.trace("currentContext token BEFORE getUserTenants...", currentContext.currentToken);
                    else
                        this.logger.trace("No currentContext BEFORE getUserTenants");
                    currentContext = yield this.establishPrincipalContext(currentContext); // shouldnt we do this before we do anything else in this class?
                    let myTenants = [];
                    if (currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentToken) {
                        myTenants = yield this.getUserTenants(this._user);
                    }
                    if (currentContext)
                        this.logger.trace("currentContext token AFTER getUserTenants...", currentContext.currentToken);
                    else
                        this.logger.trace("No currentContext AFTER getUserTenants");
                    if (myTenants && myTenants.length > 0) {
                        let tenantCode = yield this.promptToSelectTenant(myTenants, allowAddNew);
                        if (tenantCode) {
                            if (tenantCode == TenantContextualizer.CODE_FOR_NEW_TENANT) {
                                tenantCode = undefined; // this will lead us to createNewTenant while still allowing us to recognize a cancel.
                            }
                            else {
                                if (!currentContext)
                                    currentContext = yield this.authenticate(); // this should never happen - we already did so to get the list of tenant profiles.
                                if (currentContext) {
                                    ultimate = yield this.trySwitchTenant(currentContext, tenantCode); // Call server if we dont already have a token for the selected tenant.
                                    if (ultimate) {
                                        // Commented out bc:  TenantContextulizer should NOT be creating a proj cfg where there wasnt one. The init command has the sole responsibility there.
                                        // if (!this.projCfg) this.projCfg = this.createDefaultProjectConfig();  // This is avoiding a corrupted project folder.
                                        // Update the project config if available
                                        if (this.projCfg && this._projCfgRepo) {
                                            this.projCfg.tenantCode = tenantCode;
                                            yield this._projCfgRepo.updateProjectConfigFile(this.projCfg);
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            this.cancel(); // user gave up: stop the bus.
                        }
                    }
                    resolve(ultimate);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Side effect: Overwrites this._user if it s able to refresh it from the auth api */
    establishPrincipalContext(context) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    if (!this._user) {
                        if (context && context.userName != codiac_relay_contracts_1.UserContext.ANONYMOUS_USERNAME && (!context.tokenExpiration || (0, utilities_1.isFuture)(context.tokenExpiration))) {
                            let refreshResult;
                            try {
                                refreshResult = yield this.userContextRepo.refreshUserContext(context);
                            }
                            catch (err) {
                                this.logger.warn(`Failed to refresh your user context, leaving your api token potentially stale, preventing further communications: ${err.message || ""}`, err);
                            }
                            // ----------------------------------------------------------------------------------
                            // TODO:  Review this logic for refresh/expiration fails 
                            //        that should run an authenticate but arent...
                            // ----------------------------------------------------------------------------------
                            if (refreshResult) {
                                if (refreshResult.user) {
                                    this.logger.debug("Setting this.User from refresh output...");
                                    this._user = refreshResult.user;
                                    this.logger.debug(`this._user profile count: ${this._user.profiles.length}`);
                                }
                                if (refreshResult.context) {
                                    this.logger.debug("Setting context from refresh output...");
                                    context = refreshResult.context;
                                }
                                // } else {
                                //   if (context.currentToken && context.currentTenantCode && context.userName) {
                                //     // Allow for use while disconnected.
                                //     // TODO:  retrieve a locally cached user object.
                                //     this._user = new User(context.currentTenantCode, "", "", "", context.userName);
                                //     this._user.profiles = [];
                                //     for (let tenantCode in context.tokens) {
                                //       this._user.profiles.push(new AccessProfile(tenantCode));
                                //     }
                                //     this.logger.warn(`Using an instance of the current user sparsely populated from cache.`);
                                //   }
                            }
                        }
                        if (!this._user) {
                            let defaultUserName = (context && context.userName != codiac_relay_contracts_1.UserContext.ANONYMOUS_USERNAME) ? context.userName : undefined;
                            let currentTenantCode = (context && context.currentTenantCode) || undefined;
                            context = yield this.authenticate(currentTenantCode, defaultUserName);
                        }
                    }
                    resolve(context);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    getUserTenants(user) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                try {
                    let myTenants = [];
                    this.logger.write(`Retrieving tenants of user [${(user === null || user === void 0 ? void 0 : user.login) || "anonymous"}]`);
                    let myAcctResult = yield this.authClient.Auth.WhoAmI({});
                    if (myAcctResult.error)
                        throw myAcctResult.error;
                    if (((_a = myAcctResult.output) === null || _a === void 0 ? void 0 : _a.profiles) && ((_b = myAcctResult.output) === null || _b === void 0 ? void 0 : _b.profiles.length) > 0) {
                        let myProfiles = myAcctResult.output.profiles;
                        // We're gonna put the tenantCode in place of the name for now cuz that's all that we get with whoami.
                        // TODO:  Consider storing AuthTenant.name with the AccessProfile entity so we can make it readable without an extra db hit. 
                        myTenants = myProfiles.map(ap => new auth_entities_1.AuthTenant(ap.tenantCode, ap.tenantCode));
                        // If we want the tenant names...
                        //   let codesCsv = myProfiles.map(p => p.tenantCode).join(",");
                        //   let criteria: TenantCriteria = { mine: true };  // <----- TODO !!!  (works off current user)  
                        //   let result = await this.apiClient.tryReadMany(AuthTenant, TenantCriteria, criteria);
                        //  OR
                        //   let result = await this.authClient.getMyTenants();
                        //   this.logger.trace("Result of attempt to get user tenants",result)
                    }
                    resolve(myTenants);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Prompts the user to select a tenant from the given list of tenantCodes.
     * Returns undefined if cancelled, and TenantContextualizer.CODE_FOR_NEW_TENANT if "register new" is selected.
     * @param tenants List of tenants from which to select.
     * @param allowAddNew Inserts an option to add a new tenant.  (NOTE: this method DOES NOT perform the add new action itself!)
    */
    promptToSelectTenant(tenants, allowAddNew = true) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let choices = tenants.map(t => {
                        return { name: t.name, value: t.code };
                    });
                    if (allowAddNew) {
                        choices.push({ name: "(Register new tenant)", value: TenantContextualizer.CODE_FOR_NEW_TENANT });
                    }
                    // this.ui.userMessage(`Your project is not assigned to a tenant.`);
                    // this.ui.userMessage(`Please assign it to one of your organizations or register a new organization...`);
                    let selected = yield this.ui.promptSelect('tenantCode', 'Select a Tenant:', choices);
                    // let result = await inquirer.prompt({ type: 'list', name: 'tenantCode', message: 'Select a Tenant:', choices: choices});
                    // let selected: string|undefined = result.tenantCode;
                    resolve(selected);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Returns a tenant context, a user context, or undefined if operation cancelled.
     * Caches the new user context.
     * Throws any exceptions.
     *
     * `unregistered` tenant code gets ignored.
     *
     * @param login
     * @param silent (optional: defaults to false) When set to true, suppresses the prompts to confirm the given defaults.  Requires defaultLogin and defaultPassword to be set.  Also requires tenantCode if the current user has more than one tenant profile and it cannot be derived decisively from the current context.
     */
    authenticate(tenantCode, login, password, silent = false) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e;
                try {
                    let defaults = { u: login, p: password, t: tenantCode };
                    let newContext;
                    do {
                        newContext = undefined;
                        defaults.t = (defaults.t !== undefined && defaults.t !== ops_1.DxConstants.UNREGISTERED_TENANT_CODE) ? defaults.t : undefined;
                        // Dump em if they didnt get fully hydrated by this point.
                        if (silent && (defaults.u === undefined || defaults.p === undefined)) {
                            throw new Error(`Cannot authenticate using "silent": both login and password must be provided.`);
                        }
                        if (!silent) {
                            this.ui.userMessage(`Please authenticate with Codiac ${(defaults.t !== undefined) ? " under tenant " + this.styler.hilite(defaults.t) : ""} (CTRL-C to cancel)`);
                            defaults.u = yield this.ui.prompt("userName", `Username: `, true, (defaults.u == codiac_relay_contracts_1.UserContext.ANONYMOUS_USERNAME) ? undefined : defaults.u);
                        }
                        if (defaults.u) {
                            if (!silent) {
                                defaults.p = (_a = defaults.p) !== null && _a !== void 0 ? _a : yield this.ui.promptPassword("password", "Password ");
                            }
                            if (defaults.p) {
                                this.logger.trace(`Authenticating against ${this.authClient.apiRootUrl}`);
                                this.ui.startSpinner("Authenticating...");
                                let authResult = yield this.authClient.Auth.Login({ login: defaults.u, password: defaults.p, tenantCode: defaults.t });
                                delete defaults.p; // force a password prompt on re-attempts
                                if ((authResult.success === true) || (authResult.output != undefined)) { // <-- api returns failure if no tenant was specified.  UI will need to hv user select one.
                                    this.ui.stopSpinner("Success!");
                                }
                                else {
                                    this.ui.stopSpinner("Failed.");
                                }
                                // this.logger.trace("", JSON.stringify(authResult, undefined, '  '));
                                if (authResult.error) {
                                    throw authResult.error;
                                }
                                else if (authResult.output) {
                                    let token = this.authClient.authToken; // we're in a success scenario - we can rely on the token being there.
                                    let exp = token ? this.authClient.extractTokenExpiration(token) : undefined;
                                    let user = authResult.output;
                                    let userName = user.login;
                                    let tenantCode = user.tenantCode;
                                    let roles = (_b = user.roles) === null || _b === void 0 ? void 0 : _b.map(r => r.name);
                                    // this.passwordLastEntered = password;  // we're gonna need this later if we need to register a new tenant (cuz the tenantRegn endpoint doent support a user token yet.)
                                    newContext = yield this.userContextRepo.saveToUserContext(newContext, userName, token, tenantCode, exp, roles);
                                    this._user = user;
                                    // PART 2: If they didnt specify a tenant.
                                    //  make em select one and switch to it.
                                    if (_.isEmpty(tenantCode)) {
                                        if (_.isEmpty(user.profiles)) {
                                            // no tenant code 
                                            this.ui.userMessage("You are not currently registered with any tenant organizations.  You will need to get invited or create your own tenant to gain access.");
                                        }
                                        else {
                                            let myTenants = user.profiles.map(p => new auth_entities_1.AuthTenant(p.tenantCode, p.tenantCode));
                                            tenantCode = yield this.promptToSelectTenant(myTenants, false);
                                            if (tenantCode == undefined)
                                                throw new Error("You must select a tenant to gain access.");
                                            this.ui.startSpinner("Setting tenant...");
                                            newContext = yield this.trySwitchTenant(newContext, tenantCode);
                                            user.roles = (_d = (_c = user.profiles.find(p => p.tenantCode)) === null || _c === void 0 ? void 0 : _c.roles) !== null && _d !== void 0 ? _d : [];
                                            this.ui.stopSpinner("done.");
                                            this._user = user;
                                        }
                                    }
                                }
                                else if (silent == true) {
                                    // Silent mode only gets one shot at this.
                                    throw new Error((_e = authResult.message) !== null && _e !== void 0 ? _e : `Authentication failed`);
                                }
                            }
                        }
                    } while (!newContext);
                    resolve(newContext);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    isNullOrEmpty(value) {
        return (value == undefined || value == "");
    }
    tryRegisterNewTenant(currentContext, companyName, tenantCode) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                try {
                    let ultimate;
                    let tenantName = companyName !== null && companyName !== void 0 ? companyName : yield this.ui.prompt("tenantName", "Enter the full name of the organization: ", true);
                    // HACK: We happen to know that the authenticate will have necessarily been run before this was called, 
                    // and we're keeping the pwd from that run in memory just so we can fire this request.
                    if (!this._user) {
                        // Wanna authenticate here?
                        throw new Error("RegisterTenant failed: No user was provided.");
                    }
                    else if (!tenantName) {
                        // this is a null gate - it can never happen bc the prompt is required;
                        throw new Error("RegisterTenant failed: No tenant name was provided.");
                    }
                    else {
                        let createNewUser = this.isNullOrEmpty(currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentToken); // we will have already established the user context
                        const request = {
                            tenantCode: tenantCode,
                            tenantName: tenantName,
                            newUser: createNewUser,
                            userName: this._user.login,
                            password: this._user.password,
                        };
                        if (currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentToken)
                            this.authClient.setUserToken(currentContext === null || currentContext === void 0 ? void 0 : currentContext.currentToken); // <-- this is brought fwd from legacy auth... Do we need to do this?
                        let tenantResult = yield this.authClient.Auth.TenantRegistration(request);
                        if (tenantResult.error) {
                            throw tenantResult.error;
                        }
                        else if (tenantResult.success && tenantResult.output) {
                            let token = this.authClient.authToken; // thats a valid force - we will def have one if the register call succeeded 
                            let exp = this.authClient.extractTokenExpiration(token);
                            let roles = this.authClient.extractRoles(token); // this._user.roles?.map(r => r.name);
                            ultimate = yield this.userContextRepo.saveToUserContext(currentContext, this._user.login, token, tenantResult.output.code, exp, roles);
                            if (this.projCfg && this._projCfgRepo) {
                                this.projCfg.tenantCode = tenantResult.output.code;
                                yield this._projCfgRepo.updateProjectConfigFile(this.projCfg);
                            }
                        }
                        else {
                            // ??  Fail?  Is this a valid scenario?
                            throw new Error("RegisterTenant failed: " + tenantResult.message + tenantResult.error);
                        }
                    }
                    resolve(ultimate);
                }
                catch (err) {
                    this.logger.debug(`Error attempting to register new tenant: ${err.message || ""}${((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) || ""}`, (err.toJSON) ? err.toJSON() : err);
                    reject(err);
                }
            }));
        });
    }
    cancel() {
        throw new Error("Action cancelled. No work was done.");
        // this._ui.userMessage("Action cancelled. No work was done.");
        // this.exit();
    }
    /** logs a user message stating that the current user
     * is not a member of the given tenant,
     * with instructions for what to do next.  */
    renderNotAMember(username, tenantCode) {
        this.ui.userMessage(`You are currently logged in as '${this.styler.hilite(username)}',`);
        this.ui.userMessage(`but you are not a member of the tenant '${this.styler.hilite(tenantCode)}'.`);
        this.ui.userMessage(`You will need to:`);
        this.ui.userMessage(`  EITHER) Log in as a different user, using...`);
        this.ui.userMessage(`    ${this.styler.hilite("cod login [yourUsername] -p [yourPassword]")},`);
        this.ui.userMessage(`  OR) Cancel and send a request to be added, using...`);
        this.ui.userMessage(`    ${this.styler.hilite(`cod request-access ${tenantCode} --role publisher`)}`);
    }
}
exports.TenantContextualizer = TenantContextualizer;
TenantContextualizer.CODE_FOR_NEW_TENANT = "** create new **";
//# sourceMappingURL=tenant-contextualizer.js.map