"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFacebookError = parseFacebookError;
exports.createAudience = createAudience;
exports.getAudience = getAudience;
exports.getApiVersion = getApiVersion;
exports.normalizeAccountId = normalizeAccountId;
const actions_core_1 = require("@segment/actions-core");
const constants_1 = require("./constants");
function parseFacebookError(error) {
    const { response: { status = undefined, data: { error: { message: fbMessage = undefined, type = undefined, code = undefined, error_user_title = undefined, error_user_msg = undefined } = {} } = {} } = {}, message: outerMessage } = (error ?? {});
    const parts = [
        error_user_title && `error_user_title: "${error_user_title}"`,
        error_user_msg && `error_user_msg: "${error_user_msg}"`,
        fbMessage && `fbmessage: "${fbMessage}"`,
        outerMessage && `message: "${outerMessage}"`,
        code && `code: "${code}"`
    ];
    const message = parts.filter(Boolean).join('. ').trim() || 'An unknown error occurred while communicating with Facebook API.';
    return {
        message,
        code: type || actions_core_1.ErrorCodes.UNKNOWN_ERROR,
        status: status ?? 400
    };
}
async function createAudience(request, name, adAccountId, description, features, statsContext) {
    if (!name) {
        return { error: { message: 'Missing audience name value', code: actions_core_1.ErrorCodes.CREATE_AUDIENCE_FAILED } };
    }
    if (!adAccountId) {
        return { error: { message: 'Missing ad account ID value', code: actions_core_1.ErrorCodes.CREATE_AUDIENCE_FAILED } };
    }
    const url = `${constants_1.BASE_URL}/${getApiVersion(features, statsContext)}/${normalizeAccountId(adAccountId)}/customaudiences`;
    const json = {
        name,
        subtype: 'CUSTOM',
        customer_file_source: 'BOTH_USER_AND_PARTNER_PROVIDED',
        ...(description ? { description } : {})
    };
    try {
        const response = await request(url, {
            method: 'post',
            json
        });
        const { id } = response.data;
        if (!id) {
            return {
                error: {
                    message: 'Invalid response from create audience request',
                    code: actions_core_1.ErrorCodes.CREATE_AUDIENCE_FAILED
                }
            };
        }
        return { data: { externalId: id } };
    }
    catch (error) {
        const { message } = parseFacebookError(error);
        return { error: { message, code: actions_core_1.ErrorCodes.CREATE_AUDIENCE_FAILED } };
    }
}
async function getAudience(request, externalId, features, statsContext) {
    const url = `${constants_1.BASE_URL}/${getApiVersion(features, statsContext)}/${externalId}?fields=id,name`;
    try {
        const response = await request(url, { method: 'GET' });
        const { id, name } = response.data;
        if (!id) {
            return { error: { message: 'Invalid response from get audience request', code: actions_core_1.ErrorCodes.GET_AUDIENCE_FAILED } };
        }
        if (externalId !== id) {
            return { error: { message: `Audience not found. Audience ID mismatch. Expected: ${externalId}, Received: ${id}`, code: actions_core_1.ErrorCodes.GET_AUDIENCE_FAILED } };
        }
        return {
            data: {
                externalId: id,
                name: name || ''
            }
        };
    }
    catch (error) {
        const { message } = parseFacebookError(error);
        return { error: { message, code: actions_core_1.ErrorCodes.GET_AUDIENCE_FAILED } };
    }
}
function getApiVersion(features, statsContext) {
    const { statsClient, tags } = statsContext || {};
    const version = features && features[constants_1.FACEBOOK_CUSTOM_AUDIENCE_FLAGON] ? constants_1.CANARY_API_VERSION : constants_1.API_VERSION;
    tags?.push(`version:${version}`);
    statsClient?.incr(`actions_facebook_custom_audience`, 1, tags);
    return version;
}
function normalizeAccountId(adAccountId) {
    return `act_${adAccountId.replace(/^act_/, '')}`;
}
//# sourceMappingURL=functions.js.map