"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processPayload = processPayload;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("../constants");
const types_1 = require("../types");
const snakeCaseToSentenceCase = (key) => {
    return (key.charAt(0).toUpperCase() + key.slice(1)).replace(/_/g, ' ');
};
const createContextForBatch = (contextKey, audienceKey, audienceId, audienceAction) => ({
    userId: contextKey,
    cohortName: snakeCaseToSentenceCase(audienceKey),
    cohortId: audienceId,
    value: audienceAction === constants_1.CONSTANTS.ADD ? true : false
});
const getContextKey = (payload) => {
    let contextKey = null;
    switch (payload.context_key) {
        case types_1.Priority.UserIdThenEmail:
            contextKey = payload.segment_user_id || payload.user_email;
            break;
        case types_1.Priority.UserIdThenAnonymousId:
            contextKey = payload.segment_user_id || payload.segment_anonymous_id;
            break;
        case types_1.Priority.UserIdThenEmailThenAnonymousId:
            contextKey = payload.segment_user_id || payload.user_email || payload.segment_anonymous_id;
            break;
        case types_1.Priority.UserIdOnly:
            contextKey = payload.segment_user_id;
            break;
        case types_1.Priority.EmailOnly:
            contextKey = payload.user_email;
            break;
        default:
            throw new actions_core_1.PayloadValidationError('Invalid Context Key priority');
    }
    if (contextKey === null)
        throw new actions_core_1.PayloadValidationError('Context Key cannot be null');
    return contextKey;
};
const parseCustomAudienceBatches = (payload, settings) => {
    const audienceMap = new Map();
    for (const p of payload) {
        const audienceId = p.segment_audience_id;
        const contextKey = getContextKey(p);
        let audienceBatch = {
            environmentId: settings.clientId,
            contextKind: p.context_kind,
            batch: []
        };
        const existingBatchForAudience = audienceMap.get(audienceId);
        if (existingBatchForAudience) {
            audienceBatch = existingBatchForAudience;
        }
        else {
            audienceMap.set(audienceId, audienceBatch);
        }
        audienceBatch.batch.push(createContextForBatch(contextKey, p.segment_audience_key, audienceId, p.audience_action));
    }
    return Array.from(audienceMap.values());
};
async function processPayload(request, settings, events) {
    const audienceBatches = parseCustomAudienceBatches(events, settings);
    const promises = [];
    for (const batch of audienceBatches) {
        if (batch.batch.length === 0) {
            continue;
        }
        const ldRequest = request(constants_1.CONSTANTS.LD_API_BASE_URL + constants_1.CONSTANTS.LD_API_CUSTOM_AUDIENCE_ENDPOINT, {
            method: 'POST',
            json: batch
        });
        promises.push(ldRequest);
    }
    return await Promise.all(promises);
}
//# sourceMappingURL=custom-audience-operations.js.map