"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateProfileListAndPet = exports.createPet = exports.petExists = void 0;
const utils_1 = require("../utils");
const upsertListMembersWaitInterval = 150;
const sendToPetWaitInterval = 150;
const getAsyncResponseWaitInterval = 60;
const petExists = async (request, settings, computationKey) => {
    const path = `/rest/api/v1.3/lists/${settings.profileListName}/listExtensions`;
    const endpoint = new URL(path, settings.baseUrl);
    const response = await request(endpoint.href, {
        method: 'GET'
    });
    const results = response.data;
    return results.find((item) => item.profileExtension?.objectName === computationKey);
};
exports.petExists = petExists;
const createPet = async (request, settings, payload) => {
    const requestBody = {
        profileExtension: {
            objectName: payload.pet_name,
            folderName: payload.folder_name || settings.defaultFolderName
        },
        fields: [
            {
                fieldName: payload.pet_name.substring(0, 30),
                fieldType: 'STR500'
            }
        ]
    };
    const path = `/rest/api/v1.3/lists/${settings.profileListName}/listExtensions`;
    const endpoint = new URL(path, settings.baseUrl);
    const response = await request(endpoint.href, {
        method: 'POST',
        body: JSON.stringify(requestBody)
    });
    return response;
};
exports.createPet = createPet;
const updateProfileListAndPet = async (request, authTokens, settings, payloads) => {
    const records = {};
    await new Promise((resolve) => setTimeout(resolve, upsertListMembersWaitInterval));
    await updateProfileListMembers(request, authTokens, settings, payloads);
    for (const payload of payloads) {
        if (!records[payload.pet_name]) {
            records[payload.pet_name] = {
                recordsWithUserId: [],
                recordsWithEmail: [],
                recordsWithRiid: []
            };
        }
        if (payload.userData.CUSTOMER_ID_) {
            records[payload.pet_name].recordsWithUserId.push(payload);
        }
        else if (payload.userData.EMAIL_ADDRESS_) {
            records[payload.pet_name].recordsWithEmail.push(payload);
        }
        else if (payload.userData.RIID_) {
            records[payload.pet_name].recordsWithRiid.push(payload);
        }
    }
    for (const [audienceKey, recordCategories] of Object.entries(records)) {
        if (recordCategories.recordsWithUserId.length > 0) {
            records[audienceKey].requestBodyUserId = buildPetUpdatePayloads(recordCategories.recordsWithUserId, 'CUSTOMER_ID', settings);
        }
        if (recordCategories.recordsWithEmail.length > 0) {
            records[audienceKey].requestBodyEmail = buildPetUpdatePayloads(recordCategories.recordsWithEmail, 'EMAIL_ADDRESS', settings);
        }
        if (recordCategories.recordsWithRiid.length > 0) {
            records[audienceKey].requestBodyRiid = buildPetUpdatePayloads(recordCategories.recordsWithRiid, 'RIID', settings);
        }
    }
    const results = [];
    for (const [computationKey, recordCategories] of Object.entries(records)) {
        if (recordCategories.requestBodyUserId) {
            results.push(await sendPetUpdate(request, authTokens, settings, computationKey, recordCategories.requestBodyUserId));
        }
        if (recordCategories.requestBodyEmail) {
            results.push(await sendPetUpdate(request, authTokens, settings, computationKey, recordCategories.requestBodyEmail));
        }
        if (recordCategories.requestBodyRiid) {
            results.push(await sendPetUpdate(request, authTokens, settings, computationKey, recordCategories.requestBodyRiid));
        }
    }
    return results;
};
exports.updateProfileListAndPet = updateProfileListAndPet;
const buildPetUpdatePayloads = (payloads, matchField, settings) => {
    const resolvedMatchType = (matchField + '_');
    const firstPayload = payloads[0];
    const records = payloads.map((payload) => {
        const field = payload.userData[resolvedMatchType];
        if (field) {
            const inAudience = payload.traits_or_props[payload.computation_key] === true ? '1' : '0';
            return [field, inAudience];
        }
    });
    const requestBodies = [];
    for (let i = 0; i < records.length; i += 200) {
        const chunk = records.slice(i, i + 200);
        const requestBody = {
            recordData: {
                fieldNames: [resolvedMatchType, firstPayload.computation_key.substring(0, 30)],
                records: chunk,
                mapTemplateName: null
            },
            insertOnNoMatch: settings.insertOnNoMatch,
            updateOnMatch: settings.updateOnMatch,
            matchColumnName1: matchField
        };
        requestBodies.push(requestBody);
    }
    return requestBodies;
};
const updateProfileListMembers = async (request, authTokens, settings, payloads) => {
    const fieldNames = ['EMAIL_ADDRESS_', 'CUSTOMER_ID_'];
    const records = [];
    for (const payload of payloads) {
        const record = [];
        for (const fieldName of fieldNames) {
            const resolvedFieldName = fieldName;
            if (payload.userData && payload.userData[resolvedFieldName]) {
                const value = payload.userData[resolvedFieldName];
                record.push(value || '');
            }
        }
        records.push(record);
    }
    for (let i = 0; i < records.length; i += 200) {
        const chunk = records.slice(i, i + 200);
        const recordData = {
            fieldNames: fieldNames,
            records: chunk,
            mapTemplateName: ''
        };
        const mergeRule = {
            insertOnNoMatch: true,
            updateOnMatch: 'REPLACE_ALL',
            matchColumnName1: settings.matchColumnName1 + '_',
            optinValue: settings.optinValue,
            optoutValue: settings.optoutValue,
            rejectRecordIfChannelEmpty: settings.rejectRecordIfChannelEmpty,
            defaultPermissionStatus: payloads[0].default_permission_status || settings.defaultPermissionStatus
        };
        const requestBody = {
            recordData,
            mergeRule
        };
        const path = `/rest/asyncApi/v1.3/lists/${settings.profileListName}/members`;
        const endpoint = new URL(path, settings.baseUrl);
        const response = await request(endpoint.href, {
            method: 'POST',
            body: JSON.stringify(requestBody)
        });
        const requestId = response.data.requestId;
        await new Promise((resolve) => setTimeout(resolve, getAsyncResponseWaitInterval));
        const asyncResponse = await (0, utils_1.getAsyncResponse)(requestId, authTokens, settings);
        await (0, utils_1.sendDebugMessageToSegmentSource)(request, requestBody, asyncResponse, settings);
    }
};
const sendPetUpdate = async (request, authTokens, settings, computationKey, requestBodies) => {
    const path = `/rest/asyncApi/v1.3/lists/${settings.profileListName}/listExtensions/${computationKey}/members`;
    const endpoint = new URL(path, settings.baseUrl);
    const responses = [];
    for (const requestBody of requestBodies) {
        await new Promise((resolve) => setTimeout(resolve, sendToPetWaitInterval * 2));
        const response = await request(endpoint.href, {
            method: 'POST',
            body: JSON.stringify(requestBody)
        });
        const requestId = response.data.requestId;
        await new Promise((resolve) => setTimeout(resolve, getAsyncResponseWaitInterval));
        const asyncResponse = await (0, utils_1.getAsyncResponse)(requestId, authTokens, settings);
        await (0, utils_1.sendDebugMessageToSegmentSource)(request, requestBody, asyncResponse, settings);
        responses.push(asyncResponse);
    }
    return responses;
};
//# sourceMappingURL=functions.js.map