"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getListName = getListName;
exports.getListPayloadType = getListPayloadType;
exports.ensureList = ensureList;
exports.sendLists = sendLists;
const actions_core_1 = require("@segment/actions-core");
const cache_functions_1 = require("../functions/cache-functions");
const constants_1 = require("../constants");
function getListName(payload) {
    const listPayloadType = getListPayloadType(payload);
    switch (listPayloadType) {
        case 'is_not_audience_payload':
            return undefined;
        case 'is_non_engage_audience_payload': {
            const listName = payload?.list_details?.list_name?.trim() || undefined;
            return listName;
        }
        case 'is_engage_audience_payload': {
            const { computation_key } = payload;
            return (payload?.list_details?.list_name || computation_key);
        }
    }
}
function getListPayloadType(payload) {
    const { list_details: { connected_to_engage_audience, list_action, list_name, should_create_list } = {}, traits_or_props, computation_class = '', computation_key = '' } = payload;
    if (connected_to_engage_audience === true
        && computation_key !== ''
        && constants_1.ENGAGE_AUDIENCE_COMPUTATION_CLASSES.includes(computation_class)
        && typeof traits_or_props === 'object'
        && typeof traits_or_props[computation_key] === 'boolean') {
        return 'is_engage_audience_payload';
    }
    else if (connected_to_engage_audience === false
        && typeof list_action === 'boolean'
        && typeof list_name === 'string'
        && list_name.trim().length > 0
        && typeof should_create_list === 'boolean') {
        return 'is_non_engage_audience_payload';
    }
    return 'is_not_audience_payload';
}
function getListAction(payload) {
    const listPayloadType = getListPayloadType(payload);
    switch (listPayloadType) {
        case 'is_not_audience_payload':
            return undefined;
        case 'is_non_engage_audience_payload':
            return payload?.list_details?.list_action;
        case 'is_engage_audience_payload': {
            const action = payload?.traits_or_props[payload.computation_key];
            return typeof action === 'boolean' ? action : undefined;
        }
    }
}
async function ensureList(client, objectType, name, shouldCreateList, subscriptionMetadata, statsContext) {
    if (!name) {
        return undefined;
    }
    if (typeof shouldCreateList !== 'boolean') {
        return undefined;
    }
    let cacheableList = (0, cache_functions_1.getListFromCache)(name, objectType, subscriptionMetadata, statsContext);
    if (cacheableList) {
        statsContext?.statsClient?.incr('cache.getListFromCache.success', 1, statsContext?.tags);
        return cacheableList;
    }
    else {
        statsContext?.statsClient?.incr('cache.getListFromCache.miss', 1, statsContext?.tags);
        cacheableList = await getListFromHubspot(client, name, objectType, statsContext);
        if (cacheableList) {
            await (0, cache_functions_1.saveListToCache)(cacheableList, subscriptionMetadata, statsContext);
            return cacheableList;
        }
        else {
            if (shouldCreateList) {
                cacheableList = await createListInHubspot(client, name, objectType, statsContext);
                if (cacheableList) {
                    await (0, cache_functions_1.saveListToCache)(cacheableList, subscriptionMetadata, statsContext);
                    return cacheableList;
                }
            }
            else {
                throw new actions_core_1.PayloadValidationError(`List with name ${name} does not exist in HubSpot. To create the list, set the 'Create List' field to true.`);
            }
        }
    }
    throw new actions_core_1.PayloadValidationError(`Failed to ensure list with name ${name} in HubSpot`);
}
async function getListFromHubspot(client, listName, objectType, statsContext) {
    try {
        const response = await client.readList(listName);
        const { listId, name, objectTypeId, processingType } = response?.data?.list;
        if (processingType != 'MANUAL') {
            statsContext?.statsClient?.incr('cache.getListFromHubspot.fail', 1, statsContext?.tags);
            return undefined;
        }
        else {
            statsContext?.statsClient?.incr('cache.getListFromHubspot.success', 1, statsContext?.tags);
            return {
                listId,
                name,
                objectType,
                objectTypeId
            };
        }
    }
    catch (err) {
        statsContext?.statsClient?.incr('cache.getListFromHubspot.error', 1, statsContext?.tags);
        return undefined;
    }
}
async function createListInHubspot(client, name, objectType, statsContext) {
    try {
        const response = await client.createList({
            name,
            objectTypeId: objectType,
            processingType: 'MANUAL'
        });
        if (response?.data.list) {
            const { listId, name, objectTypeId } = response.data.list;
            statsContext?.statsClient?.incr('cache.createListInHubspot.success', 1, statsContext?.tags);
            return {
                listId,
                name,
                objectType: objectType,
                objectTypeId
            };
        }
        statsContext?.statsClient?.incr('cache.createListInHubspot.fail', 1, statsContext?.tags);
        return undefined;
    }
    catch (err) {
        statsContext?.statsClient?.incr('cache.createListInHubspot.error', 1, statsContext?.tags);
        if (err?.response?.data?.subCategory === 'ILS.DUPLICATE_LIST_NAMES') {
            throw new actions_core_1.RetryableError('Failed to create list: a list with this name already exists.');
        }
        throw err;
    }
}
async function sendLists(client, cachableList, fromRecordPayloads) {
    const json = {
        recordIdsToAdd: fromRecordPayloads
            .filter((p) => getListAction(p) == true)
            .map((p) => p.object_details.record_id),
        recordIdsToRemove: fromRecordPayloads
            .filter((p) => getListAction(p) == false)
            .map((p) => p.object_details.record_id)
    };
    await client.addRemoveFromList(cachableList.listId, json);
}
//# sourceMappingURL=hubspot-list-functions.js.map