"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 utils_rt_1 = require("./utils-rt");
const updateSegment_1 = __importDefault(require("./updateSegment"));
const utils_tax_1 = require("./utils-tax");
const destination = {
    name: 'Yahoo Audiences',
    slug: 'actions-yahoo-audiences',
    mode: 'cloud',
    description: 'Sync users to Yahoo Ads',
    authentication: {
        scheme: 'oauth2',
        fields: {
            mdm_id: {
                label: 'MDM ID',
                description: 'Yahoo MDM ID provided by Yahoo representative',
                type: 'string',
                required: true
            },
            engage_space_id: {
                label: 'Engage Space Id',
                description: 'Engage Space Id found in Unify > Settings > API Access',
                type: 'string',
                required: true
            },
            customer_desc: {
                label: 'Customer Description',
                description: 'Engage space name and description',
                type: 'string',
                required: false
            }
        },
        testAuthentication: async (request, { settings }) => {
            if (!process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_SECRET) {
                throw new actions_core_1.IntegrationError('Missing Taxonomy API client secret', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_ID) {
                throw new actions_core_1.IntegrationError('Missing Taxonomy API client Id', 'MISSING_REQUIRED_FIELD', 400);
            }
            const tx_creds = {
                tx_client_key: process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_ID,
                tx_client_secret: process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_SECRET
            };
            const body_form_data = (0, utils_tax_1.gen_customer_taxonomy_payload)(settings);
            if (!/^[A-Za-z0-9_]+$/.test(settings.engage_space_id)) {
                throw new actions_core_1.IntegrationError('Invalid Engage Space Id setting. Engage Space Id can be located in Unify > Settings > API Access', 'INVALID_GLOBAL_SETTING', 400);
            }
            else {
                return await (0, utils_tax_1.update_taxonomy)('', tx_creds, request, body_form_data, undefined, undefined);
            }
        },
        refreshAccessToken: async (request, { auth }) => {
            let rt_client_key = '';
            let rt_client_secret = '';
            try {
                rt_client_key = JSON.parse(auth.clientId)['rt_api'];
                rt_client_secret = JSON.parse(auth.clientSecret)['rt_api'];
            }
            catch (err) {
                rt_client_key = auth.clientId;
                rt_client_secret = auth.clientSecret;
            }
            const jwt = (0, utils_rt_1.generate_jwt)(rt_client_key, rt_client_secret);
            const res = await request('https://id.b2b.yahooinc.com/identity/oauth2/access_token', {
                method: 'POST',
                body: new URLSearchParams({
                    client_assertion: jwt,
                    client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
                    grant_type: 'client_credentials',
                    scope: 'audience',
                    realm: 'dataxonline'
                })
            });
            const rt_access_token = res.data.access_token;
            return { accessToken: rt_access_token };
        }
    },
    audienceFields: {
        placeholder: {
            type: 'boolean',
            label: 'Placeholder Setting',
            description: 'Placeholder field to allow the audience to be created. Do not change this',
            default: true
        }
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const personas = createAudienceInput.personas;
            if (!personas) {
                throw new actions_core_1.IntegrationError('Missing computation parameters: Id and Key', 'MISSING_REQUIRED_FIELD', 400);
            }
            const engage_space_id = createAudienceInput.settings?.engage_space_id;
            const audience_id = personas.computation_id;
            const audience_key = personas.computation_key;
            const statsClient = createAudienceInput?.statsContext?.statsClient;
            const statsTags = createAudienceInput?.statsContext?.tags;
            if (!engage_space_id) {
                throw new actions_core_1.IntegrationError('Create Audience: missing setting "Engage space Id" ', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_SECRET) {
                throw new actions_core_1.IntegrationError('Missing Taxonomy API client secret', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_ID) {
                throw new actions_core_1.IntegrationError('Missing Taxonomy API client Id', 'MISSING_REQUIRED_FIELD', 400);
            }
            const input = {
                segment_audience_id: audience_id,
                segment_audience_key: audience_key,
                engage_space_id: engage_space_id
            };
            const body_form_data = (0, utils_tax_1.gen_segment_subtaxonomy_payload)(input);
            const tx_creds = {
                tx_client_key: process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_ID,
                tx_client_secret: process.env.ACTIONS_YAHOO_AUDIENCES_TAXONOMY_CLIENT_SECRET
            };
            await (0, utils_tax_1.update_taxonomy)(engage_space_id, tx_creds, request, body_form_data, statsClient, statsTags);
            return { externalId: audience_id };
        },
        async getAudience(_, getAudienceInput) {
            const audience_id = getAudienceInput.externalId;
            if (!audience_id) {
                throw new actions_core_1.IntegrationError('Missing audience_id value', 'MISSING_REQUIRED_FIELD', 400);
            }
            return { externalId: audience_id };
        }
    },
    actions: {
        updateSegment: updateSegment_1.default
    },
    presets: [
        {
            name: 'Entities Audience Membership Changed',
            partnerAction: 'updateSegment',
            mapping: (0, actions_core_1.defaultValues)(updateSegment_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_audience_membership_changed_identify'
        },
        {
            name: 'Associated Entity Added',
            partnerAction: 'updateSegment',
            mapping: (0, actions_core_1.defaultValues)(updateSegment_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_added_track'
        },
        {
            name: 'Associated Entity Removed',
            partnerAction: 'updateSegment',
            mapping: (0, actions_core_1.defaultValues)(updateSegment_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'warehouse_entity_removed_track'
        },
        {
            name: 'Journeys Step Entered',
            partnerAction: 'updateSegment',
            mapping: (0, actions_core_1.defaultValues)(updateSegment_1.default.fields),
            type: 'specificEvent',
            eventSlug: 'journeys_step_entered_track'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map