"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendToPet = exports.createPet = exports.getAllPets = void 0;
const actions_core_1 = require("@segment/actions-core");
const utils_1 = require("../utils");
const getAllPets = async (request, settings) => {
    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;
    const filteredResults = results.filter((item) => item && item.profileExtension !== undefined);
    return filteredResults.map((item) => item.profileExtension);
};
exports.getAllPets = getAllPets;
const createPet = async (request, settings, petName, fields, folderName) => {
    const petFields = fields.map((field) => {
        return {
            fieldName: field.substring(0, 30),
            fieldType: 'STR500'
        };
    });
    const requestBody = {
        profileExtension: {
            objectName: petName,
            folderName: folderName || settings.defaultFolderName
        },
        fields: petFields
    };
    const path = `/rest/api/v1.3/lists/${settings.profileListName}/listExtensions`;
    const endpoint = new URL(path, settings.baseUrl);
    await request(endpoint.href, {
        method: 'POST',
        body: JSON.stringify(requestBody)
    });
};
exports.createPet = createPet;
const sendToPet = async (request, authTokens, payload, settings, userDataFieldNames) => {
    const usingAsyncApi = payload.length > 0 ? payload[0].use_responsys_async_api : false;
    const getAllPetsWaitInterval = 60;
    const createPetWaitInterval = 6000;
    const sendToPetWaitInterval = 120;
    await (0, utils_1.upsertListMembers)(request, authTokens, payload, settings, usingAsyncApi);
    const folderRecords = {};
    for (const item of payload) {
        const petName = String(item.pet_name || settings.profileExtensionTable);
        const folderName = String(item.folder_name || settings.defaultFolderName);
        if (!folderRecords[folderName]) {
            folderRecords[folderName] = {};
        }
        if (!folderRecords[folderName][petName]) {
            folderRecords[folderName][petName] = [];
        }
        folderRecords[folderName][petName].push(item.stringify ? (0, utils_1.stringifyObject)(item.userData) : item.userData);
    }
    await new Promise((resolve) => setTimeout(resolve, getAllPetsWaitInterval));
    const allPets = await (0, exports.getAllPets)(request, settings);
    const responses = [];
    for (const [folderName, petRecords] of Object.entries(folderRecords)) {
        for (const [petName, records] of Object.entries(petRecords)) {
            const correspondingPet = allPets.find((item) => item.objectName === petName);
            if (correspondingPet && correspondingPet.folderName !== folderName) {
                throw new actions_core_1.IntegrationError(`PET ${petName} already exists in another folder: ${correspondingPet.folderName}, not ${folderName}.`, 'INVALID_ARGUMENT', 400);
            }
            if (!correspondingPet) {
                await new Promise((resolve) => setTimeout(resolve, createPetWaitInterval));
                await (0, exports.createPet)(request, settings, petName, userDataFieldNames, folderName);
                allPets.push({ objectName: petName, folderName });
            }
            const resolvedRecords = records.map((userData) => {
                return userDataFieldNames.map((fieldName) => {
                    return fieldName in userData ? userData[fieldName] : '';
                });
            });
            for (let i = 0; i < resolvedRecords.length; i += 200) {
                const chunk = resolvedRecords.slice(i, i + 200);
                const recordData = {
                    fieldNames: userDataFieldNames.map((field) => field.toUpperCase()),
                    records: chunk,
                    mapTemplateName: ''
                };
                const requestBody = {
                    recordData,
                    insertOnNoMatch: settings.insertOnNoMatch,
                    updateOnMatch: settings.updateOnMatch || 'REPLACE_ALL',
                    matchColumnName1: settings.matchColumnName1,
                    matchColumnName2: settings.matchColumnName2 || ''
                };
                const path = `/rest/${usingAsyncApi ? 'asyncApi' : 'api'}/v1.3/lists/${settings.profileListName}/listExtensions/${petName}/members`;
                const endpoint = new URL(path, settings.baseUrl);
                await new Promise((resolve) => setTimeout(resolve, sendToPetWaitInterval * 2));
                const response = await request(endpoint.href, {
                    method: 'POST',
                    skipResponseCloning: true,
                    body: JSON.stringify(requestBody)
                });
                if (usingAsyncApi) {
                    const requestId = response.data.requestId;
                    const asyncResponse = await (0, utils_1.getAsyncResponse)(requestId, authTokens, settings);
                    await (0, utils_1.sendDebugMessageToSegmentSource)(request, requestBody, asyncResponse, settings);
                    responses.push(asyncResponse);
                }
                await (0, utils_1.sendDebugMessageToSegmentSource)(request, requestBody, response, settings);
                responses.push(response);
            }
        }
        return responses;
    }
};
exports.sendToPet = sendToPet;
//# sourceMappingURL=functions.js.map