"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ElectronProtocolUrl = exports.SENDER = exports.DEFAULT_WIDTH = exports.DEFAULT_HEIGHT = void 0;
exports.trainNewTest = trainNewTest;
exports.getInitialFlows = getInitialFlows;
exports.editTest = editTest;
const branches_1 = require("../../util/branches/branches");
const testsUtil_1 = require("../execution/testsUtil");
const mablApi_1 = require("../../mablApi");
const constants_1 = require("../constants");
const util_1 = require("../util");
const openUtils_1 = require("./openUtils");
const flowResolver_1 = require("../../util/flowResolver");
const loggingProvider_1 = require("../../providers/logging/loggingProvider");
const rbacUtils_1 = require("../../util/rbacUtils");
const chalk = require('chalk');
exports.DEFAULT_HEIGHT = 1440;
exports.DEFAULT_WIDTH = 1080;
exports.SENDER = 'cli';
var ElectronProtocolUrl;
(function (ElectronProtocolUrl) {
    ElectronProtocolUrl["EDIT_TEST"] = "editTest";
    ElectronProtocolUrl["TRAIN_NEW_TEST"] = "trainNewTest";
})(ElectronProtocolUrl || (exports.ElectronProtocolUrl = ElectronProtocolUrl = {}));
async function trainNewTest(trainingSessionOptions, mablApiClient, waitProcessToExit = true) {
    const apiClient = mablApiClient ??
        (await (0, util_1.getApiClientFromOptions)(trainingSessionOptions, true));
    const branchName = trainingSessionOptions.branchName ?? constants_1.DefaultBranchName;
    const { authToken, autoBranch, dataTableIds, intent: testIntent, ...passThroughFields } = trainingSessionOptions;
    const { apiDescription, applicationId, autoLogin, credentialsId, environmentId, height, planId, testDescription, testName, url, width, testType, workspaceId, } = passThroughFields;
    if (branchName !== 'master') {
        await (0, branches_1.checkBranchNameAndAutoBranchMaybe)(workspaceId, apiClient, branchName, autoBranch);
    }
    if (environmentId) {
        await apiClient.getEnvironment(environmentId);
    }
    if (planId) {
        await apiClient.getPlan(planId);
    }
    if (credentialsId) {
        const credential = await apiClient.getCredential(credentialsId);
        if (credential.cloud_only) {
            loggingProvider_1.logger.error(chalk.red.bold(`Cannot use Cloud Credentials in the trainer. Use a basic one instead.`));
            process.exit(1);
        }
    }
    await (0, rbacUtils_1.dataTablesRbacPreflight)(apiClient, dataTableIds);
    if (applicationId) {
        await apiClient.getApplication(applicationId);
    }
    const account = await apiClient.getAccountByWorkspaceId(workspaceId);
    const flows = await getInitialFlows(apiClient, autoLogin, workspaceId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Creating test in desktop app: `, testName);
    (0, testsUtil_1.logTestInfoIfPresent)(`Add auto login flow: `, autoLogin);
    (0, testsUtil_1.logTestInfoIfPresent)(`URL: `, url);
    (0, testsUtil_1.logTestInfoIfPresent)(`Workspace: `, workspaceId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Account ID: `, account.id);
    (0, testsUtil_1.logTestInfoIfPresent)(`Branch: `, branchName);
    (0, testsUtil_1.logTestInfoIfPresent)(`Plan ID: `, planId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Application ID: `, applicationId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Environment ID: `, environmentId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Credentials ID: `, credentialsId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Datatable ID(s): `, dataTableIds?.join(', '));
    (0, testsUtil_1.logTestInfoIfPresent)(`Test description: `, testDescription);
    (0, testsUtil_1.logTestInfoIfPresent)(`Test type: `, testType);
    (0, testsUtil_1.logTestInfoIfPresent)(`API description: `, apiDescription);
    const scriptConfig = {
        ...passThroughFields,
        accountId: account.id,
        branchName,
        dataTables: dataTableIds,
        flows,
        height: height ?? exports.DEFAULT_HEIGHT,
        testIntent,
        sender: exports.SENDER,
        width: width ?? exports.DEFAULT_WIDTH,
    };
    return (0, openUtils_1.openUrlInDesktopApp)(ElectronProtocolUrl.TRAIN_NEW_TEST, scriptConfig, waitProcessToExit);
}
async function getInitialFlows(apiClient, autoLogin, workspaceId) {
    const initialFlows = [];
    if (autoLogin) {
        const loginFlows = await apiClient.getFlows({
            flow_type: 'login',
            organization_id: workspaceId,
        });
        if (loginFlows?.[0]) {
            initialFlows.push(loginFlows[0].id);
        }
    }
    return initialFlows;
}
async function editTest(trainingSessionOptions) {
    const apiClient = await (0, util_1.getApiClientFromOptions)(trainingSessionOptions, true);
    let testRunIdConfig = { testId: '', filterHttpRequests: false };
    if (trainingSessionOptions.testRunId) {
        testRunIdConfig = await (0, testsUtil_1.pullDownTestRunConfig)(trainingSessionOptions.testRunId, apiClient);
    }
    const url = trainingSessionOptions.url ?? testRunIdConfig.url;
    const credentialsId = trainingSessionOptions.credentialsId ?? testRunIdConfig.credentialsId;
    const branchName = trainingSessionOptions.branchName ??
        testRunIdConfig.branchName ??
        constants_1.DefaultBranchName;
    const environmentId = trainingSessionOptions.environmentId ?? testRunIdConfig.environmentId;
    if (credentialsId) {
        const credential = await apiClient.getCredential(credentialsId);
        if (credential.cloud_only) {
            loggingProvider_1.logger.error(chalk.red.bold(`Cannot use Cloud Credentials in the trainer. Use a basic one instead.`));
            process.exit(1);
        }
    }
    const testId = trainingSessionOptions.testId ?? testRunIdConfig.testId;
    if (!testId) {
        throw new Error('Unable to determine test Id run');
    }
    const test = await apiClient.getJourney(testId, branchName);
    if (test.default) {
        throw new Error('Editing of the mabl default supplied tests is not supported');
    }
    await (0, rbacUtils_1.dataTablesRbacPreflight)(apiClient, test?.datatables);
    if (!test.flows?.length && test.test_type !== mablApi_1.TestTypeEnum.Performance) {
        throw new Error(flowResolver_1.TEST_WITHOUT_FLOWS_MESSAGE);
    }
    const workspaceId = test.organization_id;
    if (branchName !== 'master') {
        await (0, branches_1.checkBranchNameAndAutoBranchMaybe)(workspaceId, apiClient, branchName, trainingSessionOptions.autoBranch);
    }
    const finalUrl = (0, testsUtil_1.getFinalUrl)(test, url);
    if (environmentId) {
        await apiClient.getEnvironment(environmentId);
    }
    const account = await apiClient.getAccountByWorkspaceId(workspaceId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Editing test in desktop app: `, `${test.name} - ${test.invariant_id}`);
    (0, testsUtil_1.logTestInfoIfPresent)(`Test description: `, test.description);
    (0, testsUtil_1.logTestInfoIfPresent)(`URL: `, finalUrl);
    (0, testsUtil_1.logTestInfoIfPresent)(`Workspace: `, workspaceId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Branch: `, branchName);
    (0, testsUtil_1.logTestInfoIfPresent)(`Environment ID: `, environmentId);
    (0, testsUtil_1.logTestInfoIfPresent)(`Credentials ID: `, credentialsId);
    const scriptConfig = {
        accountId: account.id,
        applicationId: trainingSessionOptions.applicationId,
        branchName,
        credentialsId,
        disableIsolation: trainingSessionOptions.disableIsolation,
        environmentId,
        height: trainingSessionOptions.height ?? exports.DEFAULT_HEIGHT,
        ignoreCertificateErrors: trainingSessionOptions.ignoreCertificateErrors,
        planId: testRunIdConfig.fromPlanId,
        sender: exports.SENDER,
        testId,
        testType: test.test_type ?? mablApi_1.TestTypeEnum.Browser,
        url: finalUrl,
        width: trainingSessionOptions.width ?? exports.DEFAULT_WIDTH,
        workspaceId,
    };
    await (0, openUtils_1.openUrlInDesktopApp)(ElectronProtocolUrl.EDIT_TEST, scriptConfig);
}
