"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const fbca_properties_1 = require("./fbca-properties");
const sync_1 = __importDefault(require("./sync"));
const fbca_operations_1 = require("./fbca-operations");
const EXTERNAL_ID_KEY = 'id';
const destination = {
    name: 'Facebook Custom Audiences (Actions)',
    slug: 'actions-facebook-custom-audiences',
    mode: 'cloud',
    description: 'The Facebook Custom Audiences destination.',
    authentication: {
        scheme: 'oauth2',
        fields: {
            retlAdAccountId: fbca_properties_1.adAccountId
        }
    },
    extendRequest({ auth }) {
        return {
            headers: {
                authorization: `Bearer ${auth?.accessToken}`
            }
        };
    },
    audienceFields: {
        engageAdAccountId: fbca_properties_1.adAccountId,
        audienceDescription: {
            type: 'string',
            label: 'Description',
            description: 'A brief description about your audience.',
            required: true
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const audienceName = createAudienceInput.audienceName;
            const adAccountId = createAudienceInput.audienceSettings?.engageAdAccountId;
            const audienceDescription = createAudienceInput.audienceSettings?.audienceDescription;
            const { features, statsContext } = createAudienceInput;
            if (!audienceName) {
                throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!adAccountId) {
                throw new actions_core_1.IntegrationError('Missing ad account ID value', 'MISSING_REQUIRED_FIELD', 400);
            }
            const createAudienceUrl = `https://graph.facebook.com/${(0, fbca_operations_1.getApiVersion)(features, statsContext)}/act_${adAccountId}/customaudiences`;
            const payload = {
                name: audienceName,
                description: audienceDescription || '',
                subtype: 'CUSTOM',
                customer_file_source: 'BOTH_USER_AND_PARTNER_PROVIDED'
            };
            let response;
            try {
                response = await request(createAudienceUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams(payload)
                });
            }
            catch (err) {
                let message = err.response?.content || err.message;
                let userTitle, userMsg;
                if (typeof message === 'string') {
                    try {
                        const parsed = JSON.parse(message);
                        if (parsed?.error) {
                            userTitle = parsed.error.error_user_title;
                            userMsg = parsed.error.error_user_msg || parsed.error.error_user_message;
                        }
                    }
                    catch (e) {
                    }
                }
                if (userTitle || userMsg) {
                    message = `${userTitle ? userTitle + ': ' : ''}${userMsg || ''}`.trim();
                }
                throw new actions_core_1.IntegrationError(String(message), 'CREATE_AUDIENCE_FAILED', 400);
            }
            const r = await response.json();
            if (!r[EXTERNAL_ID_KEY]) {
                throw new actions_core_1.IntegrationError('Invalid response from create audience request', 'INVALID_RESPONSE', 400);
            }
            return {
                externalId: r[EXTERNAL_ID_KEY]
            };
        },
        async getAudience(request, getAudienceInput) {
            const { features, statsContext } = getAudienceInput;
            const getAudienceUrl = `https://graph.facebook.com/${(0, fbca_operations_1.getApiVersion)(features, statsContext)}/${getAudienceInput.externalId}`;
            const response = await request(getAudienceUrl, { method: 'GET' });
            const r = await response.json();
            if (!r[EXTERNAL_ID_KEY]) {
                throw new actions_core_1.IntegrationError('Invalid response from get audience request', 'INVALID_RESPONSE', 400);
            }
            if (getAudienceInput.externalId !== r[EXTERNAL_ID_KEY]) {
                throw new actions_core_1.IntegrationError("Couldn't find audience", 'INVALID_RESPONSE', 400);
            }
            return {
                externalId: r[EXTERNAL_ID_KEY]
            };
        }
    },
    actions: {
        sync: sync_1.default
    },
    presets: [
        {
            name: 'Entities Audience Membership Changed',
            partnerAction: 'sync',
            mapping: (0, actions_core_1.defaultValues)(sync_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_membership_changed_identify'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'sync',
            mapping: (0, actions_core_1.defaultValues)(sync_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'sync',
            mapping: (0, actions_core_1.defaultValues)(sync_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'sync',
            mapping: (0, actions_core_1.defaultValues)(sync_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map