"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.INVALID_AUTH_ERROR = void 0;
exports.getApiClient = getApiClient;
exports.getApiClientFromOptions = getApiClientFromOptions;
exports.validateAuthentication = validateAuthentication;
exports.jsonCloneDeep = jsonCloneDeep;
const mablApiClientFactory_1 = require("../api/mablApiClientFactory");
const asyncUtil_1 = require("../util/asyncUtil");
const authenticationProvider_1 = require("../providers/authenticationProvider");
const types_1 = require("../api/types");
const mablApi_1 = require("../mablApi");
const chalk_1 = __importDefault(require("chalk"));
const DEFAULT_ASYNC_TIMEOUT_MILLIS = 120_000;
exports.INVALID_AUTH_ERROR = `Auth with user credentials required. Please run ${chalk_1.default.magenta('mabl auth login')} to log in with your mabl account`;
async function getApiClient(options = {}) {
    const { asyncTimeoutMillis, authenticationConfig, runOptions, userAuthOnly, validateAuth, } = options;
    const apiClient = await (0, asyncUtil_1.promiseWithTimeout)(getApiClientFromOptions(runOptions, userAuthOnly), asyncTimeoutMillis ?? DEFAULT_ASYNC_TIMEOUT_MILLIS, 'Get API client from options');
    if (validateAuth ?? true) {
        await (0, asyncUtil_1.promiseWithTimeout)(validateAuthentication(apiClient, authenticationConfig ??
            (await (0, asyncUtil_1.promiseWithTimeout)(new authenticationProvider_1.AuthenticationProvider().getAuthConfigWithAutoRenew(), DEFAULT_ASYNC_TIMEOUT_MILLIS, 'Get auth config with auto renew'))), asyncTimeoutMillis ?? DEFAULT_ASYNC_TIMEOUT_MILLIS, 'Validate auth');
    }
    return apiClient;
}
async function getApiClientFromOptions(trainingSessionOptions, userAuthOnly) {
    if (trainingSessionOptions?.authToken) {
        return mablApiClientFactory_1.MablApiClientFactory.createApiClientForAccessToken(trainingSessionOptions.authToken);
    }
    if (userAuthOnly) {
        return mablApiClientFactory_1.MablApiClientFactory.createUserApiClient();
    }
    return mablApiClientFactory_1.MablApiClientFactory.createApiClient();
}
async function validateAuthentication(apiClient, authConfig) {
    if (authConfig.authType !== types_1.AuthType.ApiKey) {
        return;
    }
    try {
        const keyDetails = await apiClient.getApiKeyDetails();
        if (keyDetails.type === mablApi_1.ApiKeyType.CommandLineInterface) {
            return;
        }
    }
    catch (_) {
    }
    throw new Error(exports.INVALID_AUTH_ERROR);
}
function jsonCloneDeep(value) {
    if (value === undefined) {
        return undefined;
    }
    return JSON.parse(JSON.stringify(value));
}
