"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveGeneratedTest = saveGeneratedTest;
const saveTest_1 = require("./test-save/saveTest");
const env_1 = require("../../env/env");
async function saveGeneratedTest(options) {
    const { apiClient, workspaceId, applicationId, url, testName, testDescription, labels, datatables, rawSteps, stepDescriptions, credentialsId, enabled, testIntent, trainingSessionId, agentSessionId, branchId, planId, devicePreset, deviceOrientation, scenarioId, existingTest, } = options;
    if (rawSteps.length === 0) {
        return { success: false, error: 'No steps to save' };
    }
    try {
        const result = await (0, saveTest_1.saveTest)({
            apiClient,
            workspaceId,
            applicationId,
            url,
            testName,
            testDescription,
            labels,
            datatables,
            steps: rawSteps,
            scriptDescription: stepDescriptions.join('\n'),
            credentialsId,
            enabled,
            testIntent,
            trainingSessionId,
            agentSessionId,
            branch: branchId,
            planId,
            devicePreset,
            deviceOrientation,
            scenarioId,
            existingTest,
        });
        if (!result.success) {
            return {
                success: false,
                error: result.error ?? 'Unknown error saving test',
            };
        }
        const test = result.test;
        const flows = result.flows ?? [];
        const primaryFlow = flows.find((f) => !f.reusable);
        return {
            success: true,
            testId: test.invariant_id,
            flowId: primaryFlow?.id,
            testUrl: result.testUrl ??
                `${env_1.BASE_APP_URL}/workspaces/${test.organization_id}/train/tests/${test.invariant_id}/current`,
            savedTest: test,
            savedFlow: primaryFlow,
        };
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error saving test';
        return {
            success: false,
            error: errorMessage,
        };
    }
}
