"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processPayload = processPayload;
exports.createAudience = createAudience;
exports.validate = validate;
exports.getIDSchema = getIDSchema;
exports.extractUsers = extractUsers;
const actions_core_1 = require("@segment/actions-core");
const api_1 = require("./api");
const hashing_utils_1 = require("../../lib/hashing-utils");
async function processPayload(request, settings, payloads, action) {
    validate(payloads);
    let selected_advertiser_id;
    let advertiser_ids;
    const isNativeFlow = 'advertiserId' in settings;
    if (isNativeFlow) {
        settings = settings;
        selected_advertiser_id = settings.advertiserId;
        advertiser_ids = [selected_advertiser_id];
    }
    else {
        settings = settings;
        const legacyPayload = payloads[0];
        if ('selected_advertiser_id' in legacyPayload) {
            selected_advertiser_id = legacyPayload.selected_advertiser_id;
        }
        advertiser_ids = settings.advertiser_ids;
    }
    const id_schema = getIDSchema(payloads[0]);
    const TikTokApiClient = new api_1.TikTokAudiences(request, selected_advertiser_id);
    const users = extractUsers(payloads);
    let res;
    if (users.length > 0) {
        const elements = {
            advertiser_ids: advertiser_ids,
            action: action,
            id_schema: id_schema,
            batch_data: users
        };
        res = await TikTokApiClient.batchUpdate(elements);
    }
    else {
        throw new actions_core_1.PayloadValidationError('At least one of Email Id or Advertising ID must be provided.');
    }
    return res;
}
async function createAudience(request, payload) {
    const TikTokApiClient = new api_1.TikTokAudiences(request, payload.selected_advertiser_id);
    return TikTokApiClient.createAudience(payload);
}
function validate(payloads) {
    if (payloads[0].send_email === false &&
        payloads[0].send_advertising_id === false &&
        payloads[0].send_phone === false) {
        throw new actions_core_1.IntegrationError('At least one of `Send Email`, `Send Phone` or `Send Advertising ID` must be set to `true`.', 'INVALID_SETTINGS', 400);
    }
}
function getIDSchema(payload) {
    const id_schema = [];
    if (payload.send_email === true) {
        id_schema.push('EMAIL_SHA256');
    }
    if (payload.send_phone === true) {
        id_schema.push('PHONE_SHA256');
    }
    if (payload.send_advertising_id === true) {
        id_schema.push('IDFA_SHA256');
    }
    return id_schema;
}
const isHashedInformation = (information) => new RegExp(/[0-9abcdef]{64}/gi).test(information);
const hash = (value) => {
    return (0, hashing_utils_1.processHashing)(value, 'sha256', 'hex');
};
function extractUsers(payloads) {
    const batch_data = [];
    payloads.forEach((payload) => {
        if (!payload.email && !payload.advertising_id) {
            return;
        }
        const user_ids = [];
        let external_audience_id;
        if ('external_audience_id' in payload) {
            external_audience_id = payload.external_audience_id;
        }
        if ('audience_id' in payload && !external_audience_id) {
            external_audience_id = payload.audience_id;
        }
        if (payload.send_email === true) {
            let email_id = {};
            if (payload.email) {
                payload.email = payload.email
                    .replace(/\+.*@/, '@')
                    .replace(/\.(?=.*@)/g, '')
                    .toLowerCase();
                let hashedEmail = payload.email;
                if (!isHashedInformation(payload.email)) {
                    hashedEmail = hash(payload.email);
                }
                email_id = {
                    id: hashedEmail,
                    audience_ids: [external_audience_id]
                };
            }
            user_ids.push(email_id);
        }
        if (payload.send_phone === true) {
            let phone_id = {};
            if (payload.phone) {
                let hashedPhone = payload.phone;
                if (!isHashedInformation(payload.phone)) {
                    hashedPhone = hash(payload.phone);
                }
                phone_id = {
                    id: hashedPhone,
                    audience_ids: [external_audience_id]
                };
            }
            user_ids.push(phone_id);
        }
        if (payload.send_advertising_id === true) {
            let advertising_id = {};
            if (payload.advertising_id) {
                advertising_id = {
                    id: hash(payload.advertising_id),
                    audience_ids: [external_audience_id]
                };
            }
            user_ids.push(advertising_id);
        }
        batch_data.push(user_ids);
    });
    return batch_data;
}
//# sourceMappingURL=functions.js.map