"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalize = void 0;
exports.generateFile = generateFile;
exports.enquoteIdentifier = enquoteIdentifier;
exports.enrichStatsContextWithMetadata = enrichStatsContextWithMetadata;
const hashing_utils_1 = require("../../lib/hashing-utils");
function generateFile(payloads) {
    const headers = new Set();
    headers.add('audience_key');
    for (const payload of payloads) {
        if (payload.unhashed_identifier_data) {
            for (const key of Object.keys(payload.unhashed_identifier_data)) {
                headers.add(key);
            }
        }
        if (payload.identifier_data) {
            for (const key of Object.keys(payload.identifier_data)) {
                headers.add(key);
            }
        }
    }
    const headerArray = Array.from(headers);
    const incomingHeaders = headerArray.filter((h) => h !== 'audience_key');
    const sortedIncomingHeaders = [...incomingHeaders].sort();
    const sortedHeaderArray = ['audience_key', ...sortedIncomingHeaders];
    let rows = Buffer.from('');
    for (let i = 0; i < payloads.length; i++) {
        const payload = payloads[i];
        const row = new Array(sortedHeaderArray.length).fill('');
        row[sortedHeaderArray.indexOf('audience_key')] = enquoteIdentifier(payload.audience_key);
        const unhashedKeys = new Set();
        if (payload.unhashed_identifier_data) {
            for (const key of Object.keys(payload.unhashed_identifier_data)) {
                const index = sortedHeaderArray.indexOf(key);
                unhashedKeys.add(key);
                if (key === 'phone_number') {
                    row[index] = `"${(0, hashing_utils_1.processHashing)(String(payload.unhashed_identifier_data[key]), 'sha1', 'hex', (value) => normalize(key, value))}"`;
                }
                else {
                    row[index] = `"${(0, hashing_utils_1.processHashing)(String(payload.unhashed_identifier_data[key]), 'sha256', 'hex', (value) => normalize(key, value))}"`;
                }
            }
        }
        if (payload.identifier_data) {
            for (const key of Object.keys(payload.identifier_data)) {
                if (!unhashedKeys.has(key)) {
                    const index = sortedHeaderArray.indexOf(key);
                    row[index] = enquoteIdentifier(String(payload.identifier_data[key]));
                }
            }
        }
        const rowBuffer = Buffer.from(row.join(payload.delimiter) + (i + 1 === payloads.length ? '' : '\n'));
        rows = Buffer.concat([rows, rowBuffer]);
    }
    rows = Buffer.concat([Buffer.from(sortedHeaderArray.join(payloads[0].delimiter) + '\n'), rows]);
    const filename = payloads[0].filename;
    return { filename, fileContents: rows };
}
function enquoteIdentifier(identifier) {
    return `"${String(identifier).replace(/"/g, '""')}"`;
}
const normalize = (key, value) => {
    switch (key) {
        case 'phone_number': {
            const phoneRegex = /(?:\+1)?\s*\(?\s*(\d+)\s*-?\)?\s*(\d+)\s*-?\s*(\d+)/;
            const match = phoneRegex.exec(value);
            if (!match || match.length < 4)
                return value;
            return match.slice(1).join('');
        }
        case 'email': {
            return value.toLowerCase().replace(/\s+/g, '');
        }
    }
    return value;
};
exports.normalize = normalize;
function enrichStatsContextWithMetadata(statsContext, subscriptionMetadata) {
    if (statsContext && subscriptionMetadata) {
        statsContext.tags = [
            ...(statsContext.tags || []),
            `actionConfigId:${subscriptionMetadata.actionConfigId}`,
            `destinationConfigId:${subscriptionMetadata.destinationConfigId}`,
            `sourceId:${subscriptionMetadata.sourceId}`,
            `actionId:${subscriptionMetadata.actionId}`
        ];
    }
}
//# sourceMappingURL=operations.js.map