"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApiVersion = exports.generateData = void 0;
const fbca_properties_1 = require("./fbca-properties");
const hashing_utils_1 = require("../../lib/hashing-utils");
const constants_1 = require("./constants");
const actions_core_1 = require("@segment/actions-core");
const generateData = (payloads) => {
    const data = new Array(payloads.length);
    payloads.forEach((payload, index) => {
        const row = new Array(fbca_properties_1.SCHEMA_PROPERTIES.length).fill('');
        Object.entries(payload).forEach(([key, value]) => {
            if (typeof value === 'object') {
                Object.entries(value).forEach(([nestedKey, value]) => {
                    appendToDataRow(nestedKey, value, row);
                });
            }
            else {
                appendToDataRow(key, value, row);
            }
        });
        data[index] = row;
    });
    return data;
};
exports.generateData = generateData;
const appendToDataRow = (key, value, row) => {
    const index = fbca_properties_1.segmentSchemaKeyToArrayIndex.get(key);
    if (index === undefined) {
        return;
    }
    if (typeof value === 'number' || ['externalId', 'mobileAdId'].includes(key)) {
        row[index] = value;
        return;
    }
    try {
        row[index] = (0, hashing_utils_1.processHashing)(value, 'sha256', 'hex', fbca_properties_1.normalizationFunctions.get(key));
    }
    catch (error) {
        if (error instanceof hashing_utils_1.EmptyValueError) {
            throw new actions_core_1.PayloadValidationError(`Invalid value for ${key}. After normalization, the value is empty. Please provide a valid ${key} value, or omit this field entirely.`);
        }
        else {
            throw error;
        }
    }
};
const getApiVersion = (features, statsContext) => {
    const statsClient = statsContext?.statsClient;
    const tags = statsContext?.tags;
    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;
};
exports.getApiVersion = getApiVersion;
class FacebookClient {
    constructor(request, adAccountId, features, statsContext) {
        this.createAudience = async (name) => {
            return await this.request(`${this.baseUrl}${this.adAccountId}/customaudiences`, {
                method: 'post',
                json: {
                    name,
                    subtype: 'CUSTOM',
                    customer_file_source: 'BOTH_USER_AND_PARTNER_PROVIDED'
                }
            });
        };
        this.getSingleAudience = async (audienceId) => {
            try {
                const fields = '?fields=id,name';
                const { data } = await this.request(`${this.baseUrl}${audienceId}${fields}`);
                return { data, error: undefined };
            }
            catch (error) {
                return { data: undefined, error: error };
            }
        };
        this.getAllAudiences = async () => {
            const { data } = await this.request(`${this.baseUrl}${this.adAccountId}/customaudiences?fields=id,name&limit=200`);
            const choices = data.data.map(({ id, name }) => ({
                value: id,
                label: name
            }));
            return {
                choices,
                error: undefined
            };
        };
        this.syncAudience = async (input) => {
            const data = (0, exports.generateData)(input.payloads);
            const app_ids = [];
            let app_ids_items = 0;
            input.payloads.forEach((payload) => {
                if (payload.appId !== undefined) {
                    app_ids_items++;
                    app_ids.push(payload.appId);
                }
                else {
                    app_ids.push('');
                }
            });
            const page_ids = [];
            let page_ids_items = 0;
            input.payloads.forEach((payload) => {
                if (payload.pageId !== undefined) {
                    page_ids_items++;
                    page_ids.push(payload.pageId);
                }
                else {
                    page_ids.push('');
                }
            });
            const params = {
                payload: {
                    schema: fbca_properties_1.SCHEMA_PROPERTIES,
                    data: data
                }
            };
            if (app_ids_items > 0) {
                params.payload.app_ids = app_ids;
            }
            if (page_ids_items > 0) {
                params.payload.page_ids = page_ids;
            }
            return await this.request(`${this.baseUrl}${input.audienceId}/users`, {
                method: input.deleteUsers === true ? 'delete' : 'post',
                json: params
            });
        };
        this.request = request;
        this.adAccountId = this.formatAdAccount(adAccountId);
        this.baseUrl = `${constants_1.BASE_URL}/${(0, exports.getApiVersion)(features, statsContext)}/`;
        this.features = features || undefined;
    }
    formatAdAccount(adAccountId) {
        if (adAccountId.startsWith('act_')) {
            return adAccountId;
        }
        return `act_${adAccountId}`;
    }
}
exports.default = FacebookClient;
//# sourceMappingURL=fbca-operations.js.map