"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 syncAudience_1 = __importDefault(require("./syncAudience"));
const constants_1 = require("./constants");
const destination = {
    name: 'Snap Audiences (Actions)',
    slug: 'actions-snap-audiences',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            ad_account_id: {
                label: 'Ad Account ID',
                description: 'The ID of the Snap Ad Account',
                required: true,
                type: 'string'
            }
        },
        refreshAccessToken: async (request, { auth }) => {
            const res = await request(constants_1.ACCESS_TOKEN_URL, {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refreshToken,
                    client_id: auth.clientId,
                    client_secret: auth.clientSecret,
                    grant_type: 'refresh_token'
                })
            });
            return { accessToken: res.data.access_token };
        }
    },
    extendRequest({ auth }) {
        return {
            headers: {
                authorization: `Bearer ${auth?.accessToken}`
            }
        };
    },
    actions: {
        syncAudience: syncAudience_1.default
    },
    presets: [
        {
            name: 'Entities Audience Membership Changed',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_membership_changed_identify'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'syncAudience',
            mapping: (0, actions_core_1.defaultValues)(syncAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        },
        {
            name: 'Sync Engage Audience',
            subscribe: 'type = "track" or type = "identify"',
            partnerAction: 'syncAudience',
            mapping: { ...(0, actions_core_1.defaultValues)(syncAudience_1.default.fields) },
            type: 'automatic'
        }
    ],
    audienceFields: {
        customAudienceName: {
            type: 'string',
            label: 'Audience Name',
            description: 'Name for the audience that will be created in Snap. Defaults to the snake_cased Segment audience name if left blank.',
            default: '',
            required: false
        },
        description: {
            type: 'string',
            label: 'Audience Description',
            description: 'Description of for the audience that will be created in Snap.',
            default: '',
            required: false
        },
        retention_in_days: {
            type: 'number',
            label: 'Retention in days',
            description: 'Number of days to retain audience members. (Default retention is lifetime represented as 9999)',
            default: 9999,
            required: false
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const { audienceName, settings: { ad_account_id } = {}, audienceSettings: { customAudienceName, description, retention_in_days } = {} } = createAudienceInput;
            if (!audienceName) {
                throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!ad_account_id) {
                throw new actions_core_1.IntegrationError('Missing Ad Account ID. Please configure the Ad Account ID in the destination settings.', 'MISSING_REQUIRED_FIELD', 400);
            }
            const json = {
                segments: [
                    {
                        name: customAudienceName || audienceName,
                        source_type: 'FIRST_PARTY',
                        ad_account_id,
                        description: description || `Audience ${audienceName} created by Segment`,
                        retention_in_days: retention_in_days || constants_1.DEFAULT_RETENTION_DAYS
                    }
                ]
            };
            const response = await request(`https://adsapi.snapchat.com/v1/adaccounts/${ad_account_id}/segments`, {
                method: 'POST',
                json
            });
            return { externalId: response.data.segments[0].segment.id };
        },
        getAudience: async (request, { externalId }) => {
            const response = await request(`https://adsapi.snapchat.com/v1/segments/${externalId}`, {
                method: 'GET'
            });
            return { externalId: response.data.segments[0].segment.id };
        }
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map