"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.send = send;
const actions_core_1 = require("@segment/actions-core");
const actions_core_2 = require("@segment/actions-core");
const constants_1 = require("../constants");
async function send(request, payload, settings, isBatch, audienceSettings) {
    const { iterableProjectType } = settings;
    const { updateExistingUsersOnly, globalUnsubscribe, campaignId } = audienceSettings || {};
    const msResponse = new actions_core_1.MultiStatusResponse();
    const listId = Number(payload[0]?.segmentAudienceId);
    const subscribers = new Map();
    const unsubscribers = new Map();
    if (isNaN(listId)) {
        payload.forEach((p, index) => {
            handleError('Invalid or missing Segment Audience ID', isBatch, msResponse, index, p, 400);
        });
        return msResponse;
    }
    payload.map((p, index) => {
        const { email, userId, segmentAudienceKey, traitsOrProperties, dataFields } = p;
        const action = traitsOrProperties[segmentAudienceKey];
        if (iterableProjectType === constants_1.CONSTANTS.USER_ID_PROJECT_TYPE && !userId) {
            handleError('User ID is required when Iterable Project Type = User ID', isBatch, msResponse, index, p);
            return;
        }
        else if (!email && !userId) {
            handleError('Either User ID or Email is required when Iterable Project Type = Hybrid', isBatch, msResponse, index, p);
            return;
        }
        if (action) {
            const subscriber = {
                ...(email ? { email } : {}),
                ...(userId ? { userId } : {}),
                ...(iterableProjectType === constants_1.CONSTANTS.USER_ID_PROJECT_TYPE ? { preferUserId: true } : {}),
                ...(dataFields && Object.entries(dataFields).length > 0 ? { dataFields } : {})
            };
            subscribers.set(index, subscriber);
        }
        else {
            const unsubscriber = {
                ...(email ? { email } : {}),
                ...(userId ? { userId } : {})
            };
            unsubscribers.set(index, unsubscriber);
        }
    });
    if (subscribers.size > 0) {
        const json = {
            listId,
            subscribers: Array.from(subscribers.values()),
            ...(typeof updateExistingUsersOnly === 'boolean' ? { updateExistingUsersOnly } : {})
        };
        await sendList(request, constants_1.CONSTANTS.SUBSCRIBE, json, subscribers, payload, isBatch, msResponse, 'IterableSubscribeError', 'An error occurred while subscribing users.');
    }
    if (unsubscribers.size > 0) {
        const json = {
            listId,
            subscribers: Array.from(unsubscribers.values()),
            ...(typeof campaignId === 'number' ? { campaignId } : {}),
            ...(typeof globalUnsubscribe === 'boolean' ? { channelUnsubscribe: globalUnsubscribe } : {})
        };
        await sendList(request, constants_1.CONSTANTS.UNSUBSCRIBE, json, unsubscribers, payload, isBatch, msResponse, 'IterableUnsubscribeError', 'An error occurred while unsubscribing users.');
    }
    if (isBatch) {
        return msResponse;
    }
}
function handleError(message, isBatch, msResponse, index, payload, status = 400, json) {
    if (!isBatch) {
        throw new actions_core_2.PayloadValidationError(message);
    }
    msResponse.setErrorResponseAtIndex(index, {
        status,
        body: payload,
        ...(typeof json === 'object' ? { sent: json } : {}),
        errormessage: message
    });
}
async function sendList(request, endpoint, json, jsonItems, payload, isBatch, msResponse, errorName, defaultErrorMessage) {
    try {
        await request(`${constants_1.CONSTANTS.API_BASE_URL}${constants_1.CONSTANTS.API_CUSTOM_AUDIENCE_ENDPOINT}/${endpoint}`, {
            method: 'post',
            skipResponseCloning: true,
            json
        });
        if (!isBatch) {
            return;
        }
        jsonItems.forEach((user, index) => {
            const p = payload[index];
            msResponse.setSuccessResponseAtIndex(index, {
                status: 200,
                body: p,
                sent: user
            });
        });
    }
    catch (error) {
        const status = error?.response?.status || 500;
        const errormessage = error?.message || defaultErrorMessage;
        if (!isBatch) {
            throw new actions_core_1.IntegrationError(errormessage, errorName, status);
        }
        jsonItems.forEach((jsonItem, index) => {
            const p = payload[index];
            handleError(errormessage, isBatch, msResponse, index, p, status, jsonItem);
        });
    }
}
//# sourceMappingURL=functions.js.map