"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const actions_core_2 = require("@segment/actions-core");
const fields_1 = require("./fields");
const utils_1 = require("../utils");
const action = {
    title: 'Sync Audiences',
    description: 'Sync users to Microsoft Bing Ads Audiences',
    fields: {
        audience_id: fields_1.audience_id,
        traits_or_props: fields_1.traits_or_props,
        audience_key: fields_1.audience_key,
        identifier_type: fields_1.identifier_type,
        email: fields_1.email,
        crm_id: fields_1.crm_id,
        enable_batching: fields_1.enable_batching,
        batch_size: fields_1.batch_size,
        computation_class: fields_1.computation_class
    },
    perform: async (request, { payload }) => {
        return await syncUser(request, [payload], false);
    },
    performBatch: async (request, { payload }) => {
        return await syncUser(request, payload, true);
    }
};
const syncUser = async (request, payload, isBatch) => {
    const msResponse = new actions_core_2.MultiStatusResponse();
    if (!Array.isArray(payload) || payload.length === 0) {
        return msResponse;
    }
    const identifierType = payload[0]?.identifier_type;
    const audienceId = payload[0]?.audience_id;
    const addMap = new Map();
    const removeMap = new Map();
    (0, utils_1.categorizePayloadByAction)(payload, addMap, removeMap);
    const addItems = Array.from(addMap.keys());
    const removeItems = Array.from(removeMap.keys());
    const addPayload = (0, utils_1.preparePayload)(audienceId, 'Add', identifierType, addItems);
    const removePayload = (0, utils_1.preparePayload)(audienceId, 'Remove', identifierType, removeItems);
    try {
        if (addMap.size > 0) {
            const response = await (0, utils_1.sendDataToMicrosoftBingAds)(request, addPayload);
            (0, utils_1.handleMultistatusResponse)(msResponse, response, addItems, addMap, payload, isBatch);
        }
        if (removeMap.size > 0) {
            const response = await (0, utils_1.sendDataToMicrosoftBingAds)(request, removePayload);
            (0, utils_1.handleMultistatusResponse)(msResponse, response, removeItems, removeMap, payload, isBatch);
        }
    }
    catch (error) {
        if (!isBatch) {
            throw error;
        }
        if (error instanceof actions_core_1.HTTPError) {
            await (0, utils_1.handleHttpError)(msResponse, error, new Map([...addMap.entries(), ...removeMap.entries()]), payload);
        }
        else {
            throw error;
        }
    }
    return msResponse;
};
exports.default = action;
//# sourceMappingURL=index.js.map