"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 helpers_1 = require("./helpers");
const uuid_1 = require("@lukeed/uuid");
const destination = {
    name: 'Dynamic Yield by Mastercard Audiences',
    slug: 'actions-dynamic-yield-audiences',
    mode: 'cloud',
    description: 'Sync [Segment Audiences](https://segment.com/docs/engage/audiences/) to Dynamic Yield by Mastercard.',
    audienceFields: {
        audience_name: {
            type: 'string',
            label: 'Audience Name',
            required: true,
            description: 'Provide a name for your Audience to be displayed in Dynamic Yield by Mastercard.'
        },
        identifier_type: {
            type: 'string',
            label: 'Segment Identifier Type (required)',
            required: true,
            description: 'The Segment identifier to send to Dynamic Yield by Mastercard. E.g. `email`, `anonymousId`, `userId` or any other custom identifier. Make sure to configure the identifier in the `Customized Setup` below so that it is sent to Dynamic Yield by Mastercard.'
        },
        dy_identifier_type: {
            type: 'string',
            label: 'Dynamic Yield Identifier Type (optional)',
            required: false,
            description: 'The name of the identifier in Dynamic Yield by Mastercard. If you leave this empty, Segment will assume that the name of the identifier in Dynamic Yield by Mastercard matches the value specified in the "Segment Identifier Type" field.'
        }
    },
    authentication: {
        scheme: 'custom',
        fields: {
            sectionId: {
                label: 'Section ID',
                description: 'Dynamic Yield by Mastercard Section ID',
                type: 'string',
                required: true
            },
            accessKey: {
                label: 'Access Key',
                description: 'Description to be added',
                type: 'password',
                required: true
            }
        }
    },
    extendRequest({ settings }) {
        let secret = undefined;
        const dataCenter = (0, helpers_1.getDataCenter)(settings.sectionId);
        switch (dataCenter) {
            case 'US':
                secret = process.env.ACTIONS_DYNAMIC_YIELD_AUDIENCES_US_CLIENT_SECRET;
                break;
            case 'EU':
                secret = process.env.ACTIONS_DYNAMIC_YIELD_AUDIENCES_EU_CLIENT_SECRET;
                break;
            case 'DEV':
                secret = process.env.ACTIONS_DYNAMIC_YIELD_AUDIENCES_DEV_CLIENT_SECRET;
                break;
        }
        if (secret === undefined) {
            throw new actions_core_1.IntegrationError('Missing Dynamic Yield by Mastercard Audiences Client Secret', 'MISSING_REQUIRED_FIELD', 400);
        }
        return {
            headers: {
                'Content-Type': 'application/json',
                Authorization: secret
            }
        };
    },
    audienceConfig: {
        mode: {
            type: 'synced',
            full_audience_sync: false
        },
        async createAudience(request, createAudienceInput) {
            const { settings, audienceSettings: { audience_name } = {}, personas } = createAudienceInput;
            if (!audience_name) {
                throw new actions_core_1.IntegrationError('Missing Audience Name', 'MISSING_REQUIRED_FIELD', 400);
            }
            if (!personas) {
                throw new actions_core_1.IntegrationError('Missing computation parameters: Id and Key', 'MISSING_REQUIRED_FIELD', 400);
            }
            const audience_id = (0, helpers_1.hashAndEncodeToInt)(personas.computation_id);
            const json = {
                type: 'audience_subscription_request',
                id: (0, uuid_1.v4)(),
                timestamp_ms: new Date().getTime(),
                account: {
                    account_settings: {
                        sectionId: (0, helpers_1.getSectionId)(settings.sectionId),
                        connectionKey: settings.accessKey
                    }
                },
                audience_id: audience_id,
                audience_name: audience_name,
                action: 'add'
            };
            const dataCenter = (0, helpers_1.getDataCenter)(settings.sectionId);
            const response = await request((0, helpers_1.getCreateAudienceURL)(dataCenter), {
                method: 'POST',
                json
            });
            const responseData = await response.json();
            if (!responseData.id) {
                throw new actions_core_1.IntegrationError(`Failed to create Audience in Dynamic Yield by Mastercard - responseData.id null or undefined`, 'DYNAMIC_YIELD_AUDIENCE_CREATION_FAILED', 400);
            }
            return {
                externalId: String(audience_id)
            };
        },
        async getAudience(_, getAudienceInput) {
            return {
                externalId: getAudienceInput.externalId
            };
        }
    },
    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'
        }
    ]
};
exports.default = destination;
//# sourceMappingURL=index.js.map