"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
exports.sendRequest = sendRequest;
exports.getJSON = getJSON;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("../constants");
async function send(request, payloads, settings, isBatch) {
    const msResponse = new actions_core_1.MultiStatusResponse();
    const addMap = new Map();
    const deleteMap = new Map();
    payloads.forEach((payload, index) => {
        const { traits_or_props, audience_name } = payload;
        const isAudienceMember = traits_or_props && typeof audience_name === 'string' && traits_or_props[audience_name] === true;
        if (isAudienceMember) {
            addMap.set(index, payload);
        }
        else {
            deleteMap.set(index, payload);
        }
    });
    const requests = [];
    if (addMap.size > 0) {
        requests.push(sendRequest(request, addMap, settings, msResponse, isBatch, 'add'));
    }
    if (deleteMap.size > 0) {
        requests.push(sendRequest(request, deleteMap, settings, msResponse, isBatch, 'remove'));
    }
    await Promise.all(requests);
    if (isBatch) {
        return msResponse;
    }
}
async function sendRequest(request, map, settings, msResponse, isBatch, action) {
    const indices = Array.from(map.keys());
    const payloads = Array.from(map.values());
    const json = getJSON(payloads, settings, action);
    try {
        await request(`${constants_1.URL}`, {
            method: 'post',
            json
        });
        for (let i = 0; i < indices.length; i++) {
            const originalIndex = indices[i];
            const { audience_name, audience_id } = payloads[i];
            msResponse.setSuccessResponseAtIndex(originalIndex, {
                status: 200,
                body: payloads[i],
                sent: {
                    device_identities: getIds(payloads[i]),
                    audiences: getAudiences(audience_id, audience_name, action)
                }
            });
        }
    }
    catch (error) {
        const { message, code, status } = error;
        if (!isBatch) {
            throw new actions_core_1.IntegrationError((message || 'Unknown error'), (code || "Error"), (status || 400));
        }
        for (let i = 0; i < indices.length; i++) {
            const originalIndex = indices[i];
            const { audience_name, audience_id } = payloads[i];
            msResponse.setErrorResponseAtIndex(originalIndex, {
                status,
                errortype: code,
                errormessage: message,
                body: payloads[i],
                sent: {
                    device_identities: getIds(payloads[i]),
                    audiences: getAudiences(audience_id, audience_name, action)
                }
            });
        }
    }
}
function getJSON(payloads, settings, action) {
    const { api_key } = settings;
    const { audience_id, audience_name } = payloads[0];
    const json = {
        api_key,
        device_identities: payloads.flatMap((payload) => {
            return getIds(payload);
        }),
        audiences: getAudiences(audience_id, audience_name, action)
    };
    return json;
}
function getIds(payload) {
    const { idfa, gaid } = payload;
    const identities = [];
    if (idfa)
        identities.push({ type: 'IDFA', value: idfa });
    if (gaid)
        identities.push({ type: 'GAID', value: gaid });
    return identities;
}
function getAudiences(audience_id, audience_name, action) {
    return [{
            audience_id: [...audience_id].reduce((h, c) => (h = (h << 5) - h + c.charCodeAt(0) | 0), 0),
            audience_name,
            action
        }];
}
//# sourceMappingURL=functions.js.map