"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const hashing_utils_1 = require("../../lib/hashing-utils");
async function send(request, settings, payload) {
    const data = createRedditPayload(payload, settings);
    return request(`https://ads-api.reddit.com/api/v2.0/conversions/events/${settings.ad_account_id}`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${settings.conversion_token}` },
        json: JSON.parse(JSON.stringify(data))
    });
}
function createRedditPayload(payloads, settings) {
    const payloadItems = [];
    payloads.forEach((payload) => {
        const { event_at, click_id, products, user, data_processing_options, screen_dimensions, event_metadata, conversion_id } = payload;
        const custom_event_name = payload.custom_event_name;
        const tracking_type = payload.tracking_type;
        const payloadItem = {
            event_at: event_at,
            event_type: {
                tracking_type: custom_event_name ? 'Custom' : tracking_type,
                custom_event_name: clean(custom_event_name)
            },
            click_id: clean(click_id),
            event_metadata: getMetadata(event_metadata, products, conversion_id),
            user: getUser(user, data_processing_options, screen_dimensions)
        };
        payloadItems.push(payloadItem);
    });
    return {
        events: payloadItems,
        test_mode: settings.test_mode,
        partner: 'SEGMENT'
    };
}
function clean(str) {
    if (str === undefined || str === null || str === '')
        return undefined;
    return str.trim();
}
function cleanNum(num) {
    if (num === undefined || num === null)
        return undefined;
    return num;
}
function getProducts(products) {
    if (!products) {
        return undefined;
    }
    return products.map((product) => {
        return {
            category: clean(product.category),
            id: clean(product.id),
            name: clean(product.name)
        };
    });
}
function getMetadata(metadata, products, conversion_id) {
    if (!metadata && !products && !conversion_id) {
        return undefined;
    }
    return {
        currency: clean(metadata?.currency),
        item_count: cleanNum(metadata?.item_count),
        value_decimal: cleanNum(metadata?.value_decimal),
        products: getProducts(products),
        conversion_id: smartHash(conversion_id, (value) => value.trim())
    };
}
function getAdId(device_type, advertising_id) {
    if (!device_type)
        return undefined;
    if (!advertising_id)
        return undefined;
    const hashedAdId = smartHash(advertising_id);
    return device_type === 'ios' ? { idfa: hashedAdId } : { aaid: hashedAdId };
}
function getDataProcessingOptions(dataProcessingOptions) {
    if (!dataProcessingOptions)
        return undefined;
    return {
        country: clean(dataProcessingOptions.country),
        modes: dataProcessingOptions.modes?.split(',').map((mode) => mode.trim()),
        region: clean(dataProcessingOptions.region)
    };
}
function getScreen(height, width) {
    if (height === undefined || width === undefined)
        return undefined;
    return {
        height,
        width
    };
}
function getUser(user, dataProcessingOptions, screenDimensions) {
    if (!user)
        return;
    return {
        ...getAdId(user.device_type, user.advertising_id),
        email: smartHash(user.email, canonicalizeEmail),
        external_id: smartHash(user.external_id, (value) => value.trim()),
        ip_address: smartHash(user.ip_address, (value) => value.trim()),
        user_agent: clean(user.user_agent),
        uuid: clean(user.uuid),
        data_processing_options: getDataProcessingOptions(dataProcessingOptions),
        screen_dimensions: getScreen(screenDimensions?.height, screenDimensions?.width),
        phone_number: smartHash(user.phone_number, cleanPhoneNumber)
    };
}
function canonicalizeEmail(value) {
    value = value.trim();
    const localPartAndDomain = value.split('@');
    const localPart = localPartAndDomain[0].replace(/\./g, '').split('+')[0];
    return `${localPart.toLowerCase()}@${localPartAndDomain[1].toLowerCase()}`;
}
const smartHash = (value, cleaningFunction) => {
    if (value === undefined)
        return;
    return (0, hashing_utils_1.processHashing)(value, 'sha256', 'hex', cleaningFunction);
};
function cleanPhoneNumber(phoneNumber) {
    if (!phoneNumber)
        return "";
    phoneNumber = phoneNumber.trim();
    const prefix = '+';
    if (phoneNumber.startsWith('+')) {
        phoneNumber = phoneNumber.slice(1);
    }
    const extensions = ['ext', 'x', 'anexo', '#', 'poste', 'int'];
    const lower = phoneNumber.toLowerCase();
    for (const keyword of extensions) {
        const index = lower.indexOf(keyword);
        if (index !== -1) {
            phoneNumber = phoneNumber.slice(0, index);
            break;
        }
    }
    const digitsOnly = phoneNumber.replace(/\D/g, '');
    return prefix + digitsOnly;
}
//# sourceMappingURL=utils.js.map