"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clean = clean;
exports.createFilename = createFilename;
exports.createHeaders = createHeaders;
exports.enquoteIdentifier = enquoteIdentifier;
exports.generateFile = generateFile;
exports.getAudienceAction = getAudienceAction;
exports.processField = processField;
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const client_1 = require("./client");
async function send(payloads, settings, rawMapping, logger, signal) {
    const { delimiter, audience_action_column_name, batch_size_column_name, filename_prefix, file_extension, sftp_folder_path } = payloads[0];
    const headers = createHeaders(rawMapping, delimiter, audience_action_column_name, batch_size_column_name);
    const rowsObservabilityArray = [];
    const fileContent = generateFile(payloads, headers, delimiter, rowsObservabilityArray, audience_action_column_name, batch_size_column_name);
    const filename = createFilename(filename_prefix, file_extension);
    const msResponse = new actions_core_1.MultiStatusResponse();
    try {
        await (0, client_1.uploadSFTP)(settings, sftp_folder_path, filename, fileContent, logger, signal);
        payloads.forEach((payload, index) => {
            const row = rowsObservabilityArray[index] ?? '';
            msResponse.setSuccessResponseAtIndex(index, {
                status: 200,
                sent: payload,
                body: `Header row = ${headers.map((header) => header.cleanName) ?? 'Headers not found'}. Row content =${row ?? 'Row content not found'}`
            });
        });
    }
    catch (error) {
        payloads.forEach((payload, index) => {
            const row = rowsObservabilityArray[index] ?? '';
            msResponse.setErrorResponseAtIndex(index, {
                status: error?.status || 400,
                errortype: error?.code || actions_core_1.ErrorCodes.BAD_REQUEST,
                errormessage: error?.message ?? 'Failed to upload file to SFTP',
                sent: payload,
                body: `Header row = ${headers.map((header) => header.cleanName) ?? 'Headers not found'}. Row content =${row ?? 'Row content not found'}`
            });
        });
    }
    return msResponse;
}
function clean(delimiter, str = '') {
    return delimiter === 'tab' ? str : str.replace(delimiter, '');
}
function createHeaders(rawMapping, delimiter, audienceActionColumnName, batchSizeColumnName) {
    const createHeader = (columnName) => ({
        cleanName: clean(delimiter, columnName),
        originalName: columnName
    });
    const headers = [];
    Object.entries(rawMapping.columns)
        .filter(([_, value]) => value !== '')
        .forEach(([column]) => {
        headers.push(createHeader(column));
    });
    if (audienceActionColumnName)
        headers.push(createHeader(audienceActionColumnName));
    if (batchSizeColumnName)
        headers.push(createHeader(batchSizeColumnName));
    if (headers.length === 0) {
        throw new actions_core_1.PayloadValidationError('No columns headers specified');
    }
    return headers;
}
function createFilename(filename_prefix, file_extension) {
    const dateSuffix = new Date().toISOString().replace(/[:.]/g, '-');
    switch (true) {
        case filename_prefix.endsWith(`.${file_extension}`):
            return filename_prefix.replace(`.${file_extension}`, `__${dateSuffix}.${file_extension}`);
        case filename_prefix !== '':
            return `${filename_prefix}__${dateSuffix}.${file_extension}`;
        default:
            return `${dateSuffix}.${file_extension}`;
    }
}
function generateFile(payloads, headers, delimiter, rowsArray, actionColName, batchColName) {
    const rows = payloads.map((payload, index) => {
        const isLastRow = index === payloads.length - 1;
        const row = headers.map((header) => {
            switch (header.originalName) {
                case actionColName:
                    return processField(getAudienceAction(payload));
                case batchColName:
                    return processField(payloads.length);
                default:
                    return processField(payload.columns[header.originalName]);
            }
        });
        return Buffer.from(`${row.join(delimiter === 'tab' ? '\t' : delimiter)}${isLastRow ? '' : '\n'}`);
    });
    rowsArray.push(...rows.map((row) => row.toString()));
    return Buffer.concat([
        Buffer.from(`${headers.map((header) => header.cleanName).join(delimiter === 'tab' ? '\t' : delimiter)}\n`),
        ...rows
    ]);
}
function processField(value) {
    return enquoteIdentifier(value === undefined || value === null
        ? ''
        : typeof value === 'object'
            ? String(JSON.stringify(value))
            : String(value));
}
function getAudienceAction(payload) {
    if (!payload.traits_or_props || !payload.computation_key) {
        return undefined;
    }
    return payload?.traits_or_props?.[payload.computation_key] ?? undefined;
}
function enquoteIdentifier(identifier) {
    return `"${String(identifier).replace(/"/g, '""')}"`;
}
//# sourceMappingURL=functions.js.map