"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveTest = saveTest;
exports.saveSimpleTest = saveSimpleTest;
const env_1 = require("../../../env/env");
const stepProcessing_1 = require("./stepProcessing");
const builders_1 = require("./builders");
const systemVariables_1 = require("../../../shared/systemVariables");
const constants_1 = require("../../../core/constants");
async function saveTest(options) {
    const { apiClient, workspaceId, steps, url, testName, applicationId, testDescription, labels, datatables, credentialsId, existingTest, branch, devicePreset, deviceOrientation, scenarioId, mobileTrainingInfo, flowIterations, flowConfigurations, appVersion, scriptDescription, enabled, testIntent, trainingSessionId, agentSessionId, } = options;
    try {
        let resolvedBranch = branch ?? (existingTest ? constants_1.DefaultBranchName : undefined);
        if (branch) {
            try {
                const branchObj = await apiClient.getBranchById(branch);
                resolvedBranch = branchObj.name ?? branch;
            }
            catch {
            }
        }
        const flowPrototype = buildFlowForSave(steps, {
            workspaceId,
            url,
            appVersion,
            mobileTrainingInfo,
            scriptDescription,
        });
        const existingPrimaryFlow = options.existingFlows?.find((f) => !f.reusable);
        const savedFlow = existingPrimaryFlow?.id
            ? await apiClient.updateFlow(existingPrimaryFlow.id, flowPrototype, resolvedBranch)
            : await createFlow(apiClient, flowPrototype, resolvedBranch);
        const deviceEmulation = devicePreset
            ? {
                device_config: {
                    name: devicePreset,
                    preset_type: devicePreset,
                },
                orientation: (deviceOrientation ??
                    'portrait_primary'),
            }
            : undefined;
        const test = await saveJourney([savedFlow], apiClient, {
            workspaceId,
            applicationId,
            testName,
            testDescription,
            labels,
            datatables,
            credentialsId,
            url,
            branch: resolvedBranch,
            existingTest,
            flowIterations,
            flowConfigurations,
            mobileTrainingInfo,
            deviceEmulation,
            scenarioId,
            appVersion,
            enabled,
            testIntent,
            trainingSessionId,
            agentSessionId,
        });
        return {
            success: true,
            test,
            flows: [savedFlow],
            testUrl: buildTestUrl(test, workspaceId),
        };
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        return {
            success: false,
            error: errorMessage,
        };
    }
}
function buildFlowForSave(steps, options) {
    const sanitizedSteps = (0, stepProcessing_1.sanitizeSelectors)(steps);
    return (0, builders_1.buildFlowObjectForApi)({
        flowType: 'mablscript',
        description: 'Generated flow',
        steps: sanitizedSteps,
        scriptDescription: options.scriptDescription,
        inputVariables: new Map(),
        outputVariables: new Set(),
        trainedAgainstUrl: options.url,
        reusable: false,
        workspaceId: options.workspaceId,
        mobileTrainingInfo: options.mobileTrainingInfo,
        appVersion: options.appVersion,
        useJsonSteps: true,
        variableDefinitions: systemVariables_1.SYSTEM_DEFAULT_VARIABLES,
    });
}
async function createFlow(apiClient, flowPrototype, branch) {
    return apiClient.createFlow(flowPrototype, branch);
}
async function saveJourney(flows, apiClient, options) {
    const journey = (0, builders_1.buildJourneyFromOptions)(flows, {
        workspaceId: options.workspaceId,
        applicationId: options.applicationId,
        testName: options.testName,
        testDescription: options.testDescription,
        labels: options.labels,
        datatables: options.datatables,
        credentialsId: options.credentialsId,
        url: options.url,
        branch: options.branch,
        existingTest: options.existingTest,
        flowIterations: options.flowIterations,
        flowConfigurations: options.flowConfigurations,
        mobileTrainingInfo: options.mobileTrainingInfo,
        deviceEmulation: options.deviceEmulation,
        scenarioId: options.scenarioId,
        appVersion: options.appVersion,
        trainingSessionId: options.trainingSessionId,
        agentSessionId: options.agentSessionId,
    });
    if (options.enabled !== undefined) {
        journey.enabled = options.enabled;
    }
    if (options.testIntent) {
        journey.intent = options.testIntent;
    }
    if (options.existingTest?.id) {
        (0, builders_1.prepareVersionedEntityForUpdate)(journey);
        return apiClient.updateJourney(options.existingTest.id, journey, undefined, options.branch);
    }
    return apiClient.createJourney(journey, options.branch);
}
function buildTestUrl(test, workspaceId) {
    if (!test.id) {
        return '';
    }
    return `${env_1.BASE_APP_URL}/workspaces/${workspaceId}/train/tests/${test.id}`;
}
async function saveSimpleTest(options) {
    return saveTest(options);
}
