"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const helpers_1 = require("../helpers");
const action = {
    title: 'Sync Audience',
    description: 'Sync users to Dynamic Yield',
    defaultSubscription: 'type = "identify" or type = "track"',
    fields: {
        message_id: {
            label: 'Message ID',
            description: 'Segment event message ID',
            type: 'string',
            unsafe_hidden: true,
            required: true,
            default: {
                '@path': '$.messageId'
            }
        },
        timestamp: {
            label: 'Timestamp',
            description: 'Segment event timestamp',
            type: 'datetime',
            unsafe_hidden: true,
            required: true,
            default: {
                '@path': '$.timestamp'
            }
        },
        external_audience_id: {
            type: 'string',
            label: 'External Audience ID',
            description: 'Unique Audience Identifier returned by the createAudience() function call.',
            required: true,
            unsafe_hidden: false,
            default: {
                '@path': '$.context.personas.external_audience_id'
            }
        },
        segment_audience_key: {
            label: 'Audience Key',
            description: 'Segment Audience key / name',
            type: 'string',
            unsafe_hidden: false,
            required: true,
            default: {
                '@path': '$.context.personas.computation_key'
            }
        },
        traits_or_props: {
            label: 'Traits or Properties',
            description: 'Traits or Properties object',
            type: 'object',
            unsafe_hidden: false,
            required: true,
            default: {
                '@if': {
                    exists: { '@path': '$.traits' },
                    then: { '@path': '$.traits' },
                    else: { '@path': '$.properties' }
                }
            }
        },
        segment_computation_action: {
            label: 'Segment Computation Action',
            description: "Hidden field used to verify that the payload is generated by an Audience. Payloads not containing computation_class = 'audience' or 'journey_step' will be dropped before the perform() fuction call.",
            type: 'string',
            unsafe_hidden: true,
            required: true,
            default: {
                '@path': '$.context.personas.computation_class'
            },
            choices: [
                { label: 'audience', value: 'audience' },
                { label: 'journey_step', value: 'journey_step' }
            ]
        },
        email: {
            label: 'Email',
            description: "User's email address",
            type: 'string',
            required: false,
            unsafe_hidden: true,
            default: {
                '@if': {
                    exists: { '@path': '$.traits.email' },
                    then: { '@path': '$.traits.email' },
                    else: { '@path': '$.context.traits.email' }
                }
            },
            category: 'hashedPII'
        },
        anonymousId: {
            label: 'Segment Anonymous Id',
            description: "User's anonymousId",
            type: 'string',
            required: false,
            unsafe_hidden: true,
            default: { '@path': '$.anonymousId' }
        },
        userId: {
            label: 'Segment User Id',
            description: "User's unique User ID",
            type: 'string',
            required: false,
            unsafe_hidden: true,
            default: { '@path': '$.userId' }
        }
    },
    perform: async (request, { audienceSettings, payload, settings }) => {
        const { external_audience_id } = payload;
        if (!audienceSettings?.audience_name) {
            throw new actions_core_1.IntegrationError('Audience Name is required', 'MISSING_REQUIRED_FIELD', 400);
        }
        if (!audienceSettings?.identifier_type) {
            throw new actions_core_1.IntegrationError('Identifier Type is required', 'MISSING_REQUIRED_FIELD', 400);
        }
        if (!external_audience_id) {
            throw new actions_core_1.IntegrationError('External Audience ID is required', 'MISSING_REQUIRED_FIELD', 400);
        }
        const audienceName = audienceSettings?.audience_name;
        const segIdType = audienceSettings?.identifier_type ?? '';
        const normalizedsegIdType = segIdType.toLowerCase().replace(/_/g, '');
        const dyIdType = audienceSettings?.dy_identifier_type;
        const audienceValue = payload.traits_or_props[payload.segment_audience_key];
        let primaryIdentifier;
        switch (normalizedsegIdType) {
            case 'email':
                primaryIdentifier = payload.email ?? undefined;
                break;
            case 'userid':
                primaryIdentifier = payload.userId ?? undefined;
                break;
            case 'anonymousid':
                primaryIdentifier = payload.anonymousId ?? undefined;
                break;
            default: {
                primaryIdentifier = payload.traits_or_props[segIdType] ?? undefined;
            }
        }
        if (!primaryIdentifier) {
            throw new actions_core_1.IntegrationError('Primary Identifier not found', 'MISSING_REQUIRED_FIELD', 400);
        }
        const dataCenter = (0, helpers_1.getDataCenter)(settings.sectionId);
        const URL = (0, helpers_1.getUpsertURL)(dataCenter);
        const json = {
            type: 'audience_membership_change_request',
            id: payload.message_id,
            timestamp_ms: new Date(payload.timestamp).getTime(),
            account: {
                account_settings: {
                    sectionId: (0, helpers_1.getSectionId)(settings.sectionId),
                    identifier: dyIdType ?? segIdType,
                    connectionKey: settings.accessKey
                }
            },
            user_profiles: [
                {
                    user_identities: [
                        {
                            type: dyIdType ?? segIdType,
                            encoding: segIdType === 'email' ? '"sha-256"' : 'raw',
                            value: segIdType === 'email' ? (0, helpers_1.hashAndEncode)(primaryIdentifier) : primaryIdentifier
                        }
                    ],
                    audiences: [
                        {
                            audience_id: Number(external_audience_id),
                            audience_name: audienceName,
                            action: audienceValue ? 'add' : 'delete'
                        }
                    ]
                }
            ]
        };
        return request(URL, {
            method: 'post',
            json
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map