"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 addUser_1 = __importDefault(require("./addUser"));
const removeUser_1 = __importDefault(require("./removeUser"));
const api_1 = require("./api");
const constants_1 = require("./constants");
const createAudience_1 = __importDefault(require("./createAudience"));
const addToAudience_1 = __importDefault(require("./addToAudience"));
const removeFromAudience_1 = __importDefault(require("./removeFromAudience"));
const destination = {
    name: 'TikTok Audiences',
    slug: 'actions-tiktok-audiences',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            advertiser_ids: {
                label: 'TikTok Advertiser IDs',
                description: 'The Advertiser IDs where audiences should be synced. Hidden in production and should not be altered by users.',
                type: 'string',
                required: false,
                multiple: true
            }
        },
        testAuthentication: async (request, { auth }) => {
            if (!auth?.accessToken) {
                throw new actions_core_1.InvalidAuthenticationError('Please authenticate via Oauth before updating other settings and/or enabling the destination.');
            }
            const TikTokApiClient = new api_1.TikTokAudiences(request);
            const response = await TikTokApiClient.getUserInfo();
            if (response.data.code !== 0) {
                throw new Error('Invalid Oauth access token. Please reauthenticate to retrieve a valid access token before updating other settings and/or enabling the destination.');
            }
        }
    },
    extendRequest({ auth }) {
        return {
            headers: {
                'Access-Token': `${auth?.accessToken}`,
                'Content-Type': 'application/json'
            }
        };
    },
    audienceFields: {
        advertiserId: {
            type: 'string',
            label: 'Advertiser ID',
            description: 'The advertiser ID to use when syncing audiences. Required if you wish to create or update an audience.'
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const audienceName = createAudienceInput.audienceName;
            const advertiserId = createAudienceInput.audienceSettings?.advertiserId;
            const statsClient = createAudienceInput?.statsContext?.statsClient;
            const statsTags = createAudienceInput?.statsContext?.tags;
            if (!audienceName) {
                throw new actions_core_1.IntegrationError('Missing audience name value', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!advertiserId) {
                throw new actions_core_1.IntegrationError('Missing advertiser ID value', 'MISSING_REQUIRED_FIELD', 400);
            }
            const response = await request(constants_1.CREATE_AUDIENCE_URL, {
                method: 'POST',
                json: {
                    custom_audience_name: audienceName,
                    advertiser_id: advertiserId,
                    action: 'create'
                }
            });
            const r = await response.json();
            if (r['message'] !== 'OK') {
                statsClient?.incr('createAudience.error', 1, statsTags);
                throw new actions_core_1.IntegrationError('Invalid response from create audience request', 'INVALID_RESPONSE', 400);
            }
            statsClient?.incr('createAudience.success', 1, statsTags);
            return {
                externalId: r.data['audience_id']
            };
        },
        async getAudience(request, getAudienceInput) {
            const url = new URL(constants_1.GET_AUDIENCE_URL);
            const audienceIds = [getAudienceInput.externalId];
            const advertiserId = getAudienceInput.audienceSettings?.advertiserId;
            const statsClient = getAudienceInput?.statsContext?.statsClient;
            const statsTags = getAudienceInput?.statsContext?.tags;
            if (!advertiserId) {
                throw new actions_core_1.IntegrationError('Unable to verify ownership over audience. Missing advertiserId.', 'INVALID_REQUEST_DATA', 400);
            }
            const params = new URLSearchParams();
            params.append('advertiser_id', advertiserId);
            params.append('custom_audience_ids', JSON.stringify(audienceIds));
            const response = await request(`${url.toString()}?${params.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });
            const r = await response.json();
            if (r['message'] !== 'OK') {
                statsClient?.incr('getAudience.error', 1, statsTags);
                throw new actions_core_1.IntegrationError('Invalid response from get audience request', 'INVALID_RESPONSE', 400);
            }
            const externalId = r.data?.list?.[0]?.audience_details?.audience_id;
            if (!externalId) {
                statsClient?.incr('getAudience.error', 1, statsTags);
                throw new actions_core_1.IntegrationError('Audience ID not found.', 'INVALID_REQUEST_DATA', 400);
            }
            if (externalId !== getAudienceInput.externalId) {
                throw new actions_core_1.IntegrationError("Unable to verify ownership over audience. Segment Audience ID doesn't match TikToks Audience ID.", 'INVALID_REQUEST_DATA', 400);
            }
            statsClient?.incr('getAudience.success', 1, statsTags);
            return {
                externalId: externalId
            };
        }
    },
    actions: {
        addToAudience: addToAudience_1.default,
        removeFromAudience: removeFromAudience_1.default,
        addUser: addUser_1.default,
        removeUser: removeUser_1.default,
        createAudience: createAudience_1.default
    },
    presets: [
        {
            name: 'Entities Audience Entered',
            partnerAction: 'addToAudience',
            mapping: (0, actions_core_1.defaultValues)(addToAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_entered_track'
        },
        {
            name: 'Entities Audience Exited',
            partnerAction: 'removeFromAudience',
            mapping: (0, actions_core_1.defaultValues)(removeFromAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_exited_track'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'addToAudience',
            mapping: (0, actions_core_1.defaultValues)(addToAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'removeFromAudience',
            mapping: (0, actions_core_1.defaultValues)(removeFromAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'addToAudience',
            mapping: (0, actions_core_1.defaultValues)(addToAudience_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map