"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IterableListsClient = void 0;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("../constants");
class IterableListsClient {
    constructor(request, settings, audienceSettings) {
        this.request = request;
        this.apiKey = settings.apiKey;
        this.updateExistingUsersOnly =
            typeof audienceSettings?.updateExistingUsersOnly === 'boolean'
                ? audienceSettings.updateExistingUsersOnly
                : undefined;
        this.globalUnsubscribe =
            typeof audienceSettings?.globalUnsubscribe === 'boolean' ? audienceSettings.globalUnsubscribe : undefined;
        this.campaignId = typeof audienceSettings?.campaignId === 'number' ? audienceSettings.campaignId : undefined;
    }
    async processPayload(payloads) {
        const subscribersGroup = new Map();
        const unsubscribersGroup = new Map();
        payloads.map((payload) => {
            const listId = payload.segmentAudienceId;
            if (payload.traitsOrProperties[payload.segmentAudienceKey] === true) {
                const subscriber = {
                    email: payload?.email ?? undefined,
                    userId: payload?.userId ?? undefined,
                    preferUserId: true
                };
                if (payload?.dataFields) {
                    subscriber.dataFields = payload.dataFields;
                }
                if (subscribersGroup.has(listId)) {
                    subscribersGroup.get(listId)?.push(subscriber);
                }
                else {
                    subscribersGroup.set(listId, [subscriber]);
                }
            }
            else {
                const subscriber = {
                    email: payload?.email ?? undefined,
                    userId: payload?.userId ?? undefined
                };
                if (unsubscribersGroup.has(listId)) {
                    unsubscribersGroup.get(listId)?.push(subscriber);
                }
                else {
                    unsubscribersGroup.set(listId, [subscriber]);
                }
            }
        });
        const subcribeRequests = [];
        const unSubcribeRequests = [];
        subscribersGroup.forEach((subscribers, listId) => {
            const json = {
                listId: Number(listId),
                subscribers,
                updateExistingUsersOnly: this.updateExistingUsersOnly
            };
            subcribeRequests.push(this.request(`${constants_1.CONSTANTS.API_BASE_URL}/lists/subscribe`, {
                method: 'post',
                skipResponseCloning: true,
                json
            }));
        });
        unsubscribersGroup.forEach((subscribers, listId) => {
            const json = {
                listId: Number(listId),
                subscribers,
                campaignId: typeof this.campaignId === 'number' ? this.campaignId : undefined,
                channelUnsubscribe: this.globalUnsubscribe
            };
            unSubcribeRequests.push(this.request(`${constants_1.CONSTANTS.API_BASE_URL}/lists/unsubscribe`, {
                method: 'post',
                skipResponseCloning: true,
                json
            }));
        });
        return await Promise.all([...unsubscribersGroup, ...subscribersGroup]);
    }
    static validate(payload) {
        if (!payload.email && !payload.userId) {
            throw new actions_core_1.PayloadValidationError('Either Email or User ID fields must be populated.');
        }
    }
}
exports.IterableListsClient = IterableListsClient;
//# sourceMappingURL=iterable-client.js.map