"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const const_1 = require("../const");
const crypto_1 = require("crypto");
const versioning_info_1 = require("../versioning-info");
async function send(request, payloads) {
    const audienceId = payloads[0].external_audience_id;
    if (!audienceId) {
        throw new actions_core_1.PayloadValidationError('External Audience ID is required.');
    }
    const validPayloads = cleanPayloads(payloads);
    const addPayloads = validPayloads.filter((p) => p.traits_or_props[p.computation_key] === true);
    const removePayloads = validPayloads.filter((p) => p.traits_or_props[p.computation_key] === false);
    const addColumns = getColumns(addPayloads);
    const removeColumns = getColumns(removePayloads);
    const addJSON = {
        data: {
            column_order: addColumns,
            user_data: addPayloads.map((p) => {
                const data = [];
                if (addColumns.includes(const_1.EMAIL_SCHEMA_NAME) && p.email) {
                    data.push(p.email ?? '');
                }
                if (addColumns.includes(const_1.MAID_SCHEMA_NAME)) {
                    data.push(p.androidIDFA ?? p.iosIDFA ?? '');
                }
                return data;
            }),
            action_type: 'ADD'
        }
    };
    if (addJSON.data.user_data.length > 0) {
        await updateAudience(request, addJSON, audienceId);
    }
    const removeJSON = {
        data: {
            column_order: removeColumns,
            user_data: removePayloads.map((p) => {
                const data = [];
                if (removeColumns.includes(const_1.EMAIL_SCHEMA_NAME) && p.email) {
                    data.push(p.email);
                }
                if (removeColumns.includes(const_1.MAID_SCHEMA_NAME)) {
                    data.push(p.androidIDFA ?? p.iosIDFA ?? '');
                }
                return data;
            }),
            action_type: 'REMOVE'
        }
    };
    if (removeJSON.data.user_data.length > 0) {
        await updateAudience(request, removeJSON, audienceId);
    }
}
function cleanPayloads(payloads) {
    const p = payloads
        .filter((payload) => payload.email || payload.iosIDFA || payload.androidIDFA)
        .map((payload) => {
        const copy = { ...payload };
        if (copy.email && !ensureHashed(copy.email)) {
            copy.email = hashEmail(copy.email);
        }
        if (copy.iosIDFA && !ensureHashed(copy.iosIDFA)) {
            const hash = (0, crypto_1.createHash)('sha256');
            hash.update(copy.iosIDFA);
            copy.iosIDFA = hash.digest('hex');
        }
        if (copy.androidIDFA && !ensureHashed(copy.androidIDFA)) {
            const hash = (0, crypto_1.createHash)('sha256');
            hash.update(copy.androidIDFA);
            copy.androidIDFA = hash.digest('hex');
        }
        return copy;
    });
    return p;
}
function getColumns(payloads) {
    const hasEmail = payloads.some((payload) => !!payload.email);
    const hasMAID = payloads.some((payload) => payload.androidIDFA || payload.iosIDFA);
    return [...(hasEmail ? [const_1.EMAIL_SCHEMA_NAME] : []), ...(hasMAID ? [const_1.MAID_SCHEMA_NAME] : [])];
}
async function updateAudience(request, json, audienceid) {
    return await request(`https://ads-api.reddit.com/api/${versioning_info_1.REDDIT_AUDIENCES_ADS_API_VERSION}/custom_audiences/${audienceid}/users`, {
        method: 'PATCH',
        json
    });
}
function ensureHashed(value) {
    const sha256HashedRegex = /^[a-f0-9]{64}$/i;
    return sha256HashedRegex.test(value);
}
function hashEmail(value) {
    const email = canonicalizeEmail(value);
    const hash = (0, crypto_1.createHash)('sha256');
    hash.update(email);
    return hash.digest('hex');
}
function canonicalizeEmail(value) {
    const localPartAndDomain = value.split('@');
    const localPart = localPartAndDomain[0].replace(/\./g, '').split('+')[0];
    return `${localPart.toLowerCase()}@${localPartAndDomain[1].toLowerCase()}`;
}
//# sourceMappingURL=functions.js.map