"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuth2Client = void 0;
const tslib_1 = require("tslib");
const inversify_1 = require("inversify");
const codiac_common_1 = require("@codiac.io/codiac-common");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
/**
 *
 * @see https://docs.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-protocols-oauth-code#request-an-authorization-code
 * @see https://docs.microsoft.com/en-us/rest/api/azure/#create-the-request
 */
let OAuth2Client = class OAuth2Client {
    constructor(logger) {
        this.logger = logger;
        this._cliExec = new codiac_ops_common_1.CliExec(logger);
    }
    /** Creates the client application for this cluster to interface with Azure AD,
     *
     * NOTE:  This method requires that the azure cli context be authenticated (via: `az login`)
     *         and the correct target subscription be set (via `az account set --subscription xyzpdq`).
     *
     * NOTE:  This command requires that the current az cli user have rights
     *        to register AD applications, as well as list and create service principals.
     *        (ie: user account must have at least the role of "Application Administrator")
     *
     * @param clientAppName  the name to give this client in Azure AD.
     * @returns client_id: The cleint app id in Azure AD required in Azure REST API requests. */
    create_client_app(clientAppName) {
        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 {
                    // TODO:  Make this idempotent
                    this.logger.detail("Creating client AD app...");
                    let cmdCreateClientApp = `az ad app create --display-name ${clientAppName} --native-app --reply-urls "https://${clientAppName}" --query appId -o tsv`;
                    let clientApplicationId = yield this._cliExec.execAsyncStdOut(cmdCreateClientApp, { cwd: process.cwd() });
                    // # Create a service principal for the client application
                    // # The app create statement is idempotent, but the sp create isnt, 
                    // # so we need to check for existence before creating...
                    let cmdFind = `az ad sp list --spn ${clientApplicationId} --query [0].objectId -o tsv`;
                    let existingId = yield this._cliExec.execAsyncStdOut(cmdFind, { cwd: process.cwd() });
                    if (existingId == "") {
                        let cmdSvcPrn = `az ad sp create --id ${clientApplicationId}`; // shouldnt we be naming this?
                        yield this._cliExec.spawnAndLog(cmdSvcPrn, process.cwd());
                        this.logger.detail("Created service principal for AD client app: " + clientApplicationId);
                    }
                    else {
                        this.logger.detail("Service principal for AD Client Application already exists: " + existingId);
                    }
                    resolve(clientApplicationId);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
};
OAuth2Client = tslib_1.__decorate([
    tslib_1.__param(0, (0, inversify_1.inject)(codiac_common_1.INTERFACES.IBetterLogger)),
    tslib_1.__metadata("design:paramtypes", [Object])
], OAuth2Client);
exports.OAuth2Client = OAuth2Client;
//# sourceMappingURL=oauth2-client.js.map