"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.performHook = performHook;
exports.getExistingAudienceIdChoices = getExistingAudienceIdChoices;
exports.getAllAudiences = getAllAudiences;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("../constants");
const functions_1 = require("../functions");
async function performHook(request, adAccountId, operation, audienceName, existingAudienceId) {
    if (operation === 'create') {
        if (!audienceName || typeof audienceName !== 'string') {
            return {
                error: {
                    message: 'Missing audience name value',
                    code: actions_core_1.ErrorCodes.RETL_ON_MAPPING_SAVE_FAILED
                }
            };
        }
        else {
            const { data: { externalId } = {}, error } = await (0, functions_1.createAudience)(request, audienceName, adAccountId);
            if (error) {
                return { error, choices: [] };
            }
            return {
                successMessage: `Audience created with ID: ${externalId}`,
                savedData: {
                    audienceId: externalId,
                    audienceName
                }
            };
        }
    }
    if (operation === 'existing') {
        if (!existingAudienceId || typeof existingAudienceId !== 'string') {
            return {
                error: {
                    message: 'Missing audience ID value',
                    code: actions_core_1.ErrorCodes.RETL_ON_MAPPING_SAVE_FAILED
                }
            };
        }
        else {
            const { data: { name } = {}, error } = await (0, functions_1.getAudience)(request, existingAudienceId);
            if (error) {
                return { error };
            }
            return {
                successMessage: `Connected to audience with ID: ${existingAudienceId}`,
                savedData: {
                    audienceId: existingAudienceId,
                    audienceName: name
                }
            };
        }
    }
    return {
        error: {
            message: 'Invalid operation value. Must be existing or create.',
            code: actions_core_1.ErrorCodes.RETL_ON_MAPPING_SAVE_FAILED
        }
    };
}
async function getExistingAudienceIdChoices(request, { settings }) {
    const { retlAdAccountId: adAccountId } = settings;
    const { choices, error } = await getAllAudiences(request, adAccountId);
    if (error) {
        return { error, choices: [] };
    }
    return {
        choices
    };
}
async function getAllAudiences(request, adAccountId, features, statsContext) {
    const url = `${constants_1.BASE_URL}/${(0, functions_1.getApiVersion)(features, statsContext)}/${(0, functions_1.normalizeAccountId)(adAccountId)}/customaudiences?fields=id,name&limit=200`;
    try {
        const { data } = await request(url);
        const choices = data.data.map(({ id, name }) => ({
            value: id,
            label: name
        }));
        if (choices.length > 0) {
            return {
                choices
            };
        }
        return {
            error: {
                message: 'No custom audiences found in this ad account. Please create an audience in Facebook before connecting it to Segment.',
                code: actions_core_1.ErrorCodes.RETL_ON_MAPPING_SAVE_FAILED
            },
            choices: []
        };
    }
    catch (error) {
        const { message, code } = (0, functions_1.parseFacebookError)(error);
        return { error: { message, code }, choices: [] };
    }
}
//# sourceMappingURL=hook-functions.js.map