"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dumpToCsv = dumpToCsv;
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const fileUtil_1 = require("../../commandUtil/fileUtil");
const js_yaml_1 = require("js-yaml");
const sync_1 = require("csv-stringify/sync");
const datatableUtil_1 = require("@mablhq-internal/runtime/util/datatableUtil");
exports.command = `export <${constants_1.CommandArgId}>`;
exports.describe = 'Export a DataTable in a specified file format';
exports.builder = (yargs) => {
    yargs
        .positional(constants_1.CommandArgId, {
        describe: 'DataTable id to export',
        type: 'string',
    })
        .option(constants_1.CommandArgFormat, {
        alias: 'fmt',
        default: constants_1.OutputFormats.Json,
        describe: `Specify a format for the DataTable export`,
        choices: [constants_1.OutputFormats.Json, constants_1.OutputFormats.Yaml, constants_1.OutputFormats.Csv],
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(exportDataTable);
async function exportDataTable(parsed) {
    const dataTableId = parsed.id;
    const format = parsed.format;
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const scenarioQueryResult = await apiClient.queryScenarios(dataTableId);
    const scenarios = scenarioQueryResult.scenarios ?? [];
    let output = '';
    switch (format) {
        case constants_1.OutputFormats.Json:
            output = dumpToJson(scenarios);
            break;
        case constants_1.OutputFormats.Yaml:
            output = dumpToYaml(scenarios);
            break;
        case constants_1.OutputFormats.Csv:
            output = dumpToCsv(scenarios);
            break;
        default:
            throw Error(`${format} is not a valid option.`);
    }
    (0, fileUtil_1.writeExportedEntityToFile)(output, format, dataTableId);
}
function toScenarioExportFormat(scenarios) {
    return scenarios.map((scenario) => ({
        id: scenario.id,
        name: scenario.name,
        variables: scenario.variables,
    }));
}
function dumpToJson(scenarios) {
    return JSON.stringify(toScenarioExportFormat(scenarios), null, 2);
}
function dumpToYaml(scenarios) {
    return (0, js_yaml_1.dump)(toScenarioExportFormat(scenarios));
}
function dumpToCsv(scenarios) {
    const output = [];
    if (scenarios.length === 0) {
        return '';
    }
    const headers = [
        constants_1.SCENARIO_ID_HEADER,
        constants_1.SCENARIO_NAME_HEADER,
        ...(scenarios[0].variables || []).map((variable) => (0, datatableUtil_1.sanitizeCsvCellInput)(variable.name || '')),
    ];
    output.push(headers);
    scenarios.forEach((scenario) => {
        const variables = scenario.variables ?? [];
        const sanitizedRowValues = [
            scenario.id,
            scenario.name,
            ...variables.map((variable) => variable.value || ''),
        ].map((val) => (0, datatableUtil_1.sanitizeCsvCellInput)(val ?? ''));
        output.push(sanitizedRowValues);
    });
    return (0, sync_1.stringify)(output);
}
