"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const emarsys_helper_1 = require("../emarsys-helper");
const action = {
    title: 'Trigger Event',
    description: 'Trigger an external event on the Emarsys platform to launch automation programs. Note: You can only pass objects to event_payload (no literals, no arrays).',
    fields: {
        eventid: {
            label: 'Id of the external event',
            description: 'The Id of the external event',
            type: 'integer',
            required: true,
            dynamic: true
        },
        key_field: {
            label: 'Key field',
            description: 'The field to use to find the contact',
            type: 'string',
            required: true,
            dynamic: true
        },
        key_value: {
            label: 'Key value',
            description: 'Value for the key field used to find the contact. E.g. the email address ',
            type: 'string',
            required: true,
            dynamic: false
        },
        event_payload: {
            label: 'Event payload',
            description: 'A JSON object that will be passed to the Emarsys template engine and can be used for personalization',
            type: 'object',
            additionalProperties: true,
            required: false,
            allowNull: true
        }
    },
    dynamicFields: {
        eventid: async (request) => {
            return (0, emarsys_helper_1.getEvents)(request);
        },
        key_field: async (request) => {
            return (0, emarsys_helper_1.getFields)(request);
        }
    },
    perform: async (request, data) => {
        data.payload.eventid = parseInt(data.payload.eventid.toString().replace(/[^0-9]/g, ''));
        if (data.payload.eventid > 0) {
            const payload = {
                key_id: data.payload.key_field,
                external_id: data.payload.key_value,
                data: data.payload.event_payload ?? null
            };
            const response = await request(`${emarsys_helper_1.API_BASE}event/${data.payload.eventid}/trigger`, {
                method: 'post',
                json: payload,
                throwHttpErrors: false
            });
            switch (response?.status) {
                case 200:
                    try {
                        const body = await response.json();
                        if (body.replyCode === 0)
                            return response;
                        else
                            throw new actions_core_1.APIError(`Something went wrong while triggering the event: ${body?.replyText ?? 'UNKNOWN'}`, 500);
                    }
                    catch (err) {
                        throw new actions_core_1.APIError('Invalid JSON response', 400);
                    }
                case 400:
                    throw new actions_core_1.APIError('The event could not be triggered', 400);
                case 429:
                    throw new actions_core_1.RetryableError('Rate limit reached.');
                default:
                    throw new actions_core_1.RetryableError('There seems to be an API issue.');
            }
        }
        else {
            throw new actions_core_1.PayloadValidationError('eventid must be >0');
        }
    },
    performBatch: async (request, data) => {
        if (data && data.payload && Array.isArray(data.payload)) {
            const batches = {};
            data.payload.forEach((payload) => {
                if (!batches[`${payload.eventid}-${payload.key_field}`]) {
                    batches[`${payload.eventid}-${payload.key_field}`] = {
                        event_id: payload.eventid,
                        key_id: payload.key_field,
                        keys: []
                    };
                }
                batches[`${payload.eventid}-${payload.key_field}`].keys.push({
                    external_id: payload.key_value,
                    data: payload.event_payload ?? null
                });
            });
            const requests = [];
            for (const key in batches) {
                const batch = batches[key];
                const payload = {
                    key_id: batch.key_id,
                    contacts: batch.keys
                };
                const response = request(`${emarsys_helper_1.API_BASE}event/${batch.event_id}/trigger`, {
                    method: 'post',
                    json: payload,
                    throwHttpErrors: false
                });
                requests.push(response);
            }
            if (requests.length > 0) {
                return Promise.all(requests);
            }
        }
        return 0;
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map