"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: 'Upsert Contact',
    description: 'Insert or update a contact on the Emarsys platform',
    fields: {
        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
        },
        write_field: {
            label: 'Fields to write',
            description: 'Use the emarsys field id (number) as key and set a value (string) (static, function or event variable)',
            type: 'object',
            required: true,
            additionalProperties: true,
            properties: {},
            default: {
                1: { '@path': '$.traits.firstName' },
                2: { '@path': '$.traits.lastName' },
                3: { '@path': '$.traits.email' }
            }
        }
    },
    dynamicFields: {
        key_field: async (request) => {
            return (0, emarsys_helper_1.getFields)(request);
        }
    },
    perform: async (request, data) => {
        const contact = {};
        contact[data.payload.key_field] = data.payload.key_value;
        Object.assign(contact, data.payload.write_field);
        const payload = {
            key_id: data.payload.key_field,
            contacts: [contact]
        };
        const response = await request(`${emarsys_helper_1.API_BASE}contact/?create_if_not_exists=1`, {
            method: 'put',
            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 upserting the contact: ${body?.replyText ?? 'UNKNOWN'}`, 500);
                }
                catch (err) {
                    throw new actions_core_1.APIError('Invalid JSON response', 400);
                }
            case 400:
                throw new actions_core_1.APIError('Contact could not be upserted', 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.');
        }
    },
    performBatch: async (request, data) => {
        if (data && data.payload && Array.isArray(data.payload)) {
            const batches = {};
            data.payload.forEach((payload) => {
                if (!batches[`${payload.key_field}`]) {
                    batches[`${payload.key_field}`] = {
                        key_id: payload.key_field,
                        contacts: []
                    };
                }
                let contact = {};
                contact[payload.key_field] = payload.key_value;
                contact = Object.assign(contact, payload.write_field);
                batches[`${payload.key_field}`].contacts.push(contact);
            });
            const requests = [];
            for (const key in batches) {
                const batch = batches[key];
                const payload = {
                    key_id: batch.key_id,
                    contacts: batch.contacts
                };
                const response = request(`${emarsys_helper_1.API_BASE}contact/?create_if_not_exists=1`, {
                    method: 'put',
                    json: payload,
                    throwHttpErrors: false
                });
                requests.push(response);
            }
            if (requests.length > 0) {
                return Promise.all(requests);
            }
        }
        return 0;
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map