"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const shared_fields_1 = require("../shared-fields");
const utils_1 = require("../utils");
const transformIterableUserPayload = (payload) => {
    const phoneNumber = payload.phoneNumber;
    delete payload.phoneNumber;
    const formattedDataFields = (0, utils_1.convertDatesInObject)(payload.dataFields ?? {});
    const userUpdateRequest = {
        ...payload,
        dataFields: {
            ...formattedDataFields,
            phoneNumber: phoneNumber
        }
    };
    return userUpdateRequest;
};
const action = {
    title: 'Upsert User',
    description: 'Creates or updates a user',
    defaultSubscription: 'type = "identify"',
    fields: {
        email: {
            ...shared_fields_1.EMAIL_FIELD,
            default: { '@path': '$.traits.email' }
        },
        userId: {
            ...shared_fields_1.USER_ID_FIELD
        },
        dataFields: {
            ...shared_fields_1.USER_DATA_FIELDS
        },
        phoneNumber: {
            ...shared_fields_1.USER_PHONE_NUMBER_FIELD
        },
        mergeNestedObjects: {
            ...shared_fields_1.MERGE_NESTED_OBJECTS_FIELD
        },
        enable_batching: {
            label: 'Enable Batching',
            description: 'When enabled, Segment will send data to Iterable in batches of up to 1001',
            type: 'boolean',
            required: false,
            default: true
        },
        batch_size: {
            label: 'Batch Size',
            description: 'Maximum number of events to include in each batch. Actual batch sizes may be lower.',
            type: 'number',
            unsafe_hidden: true,
            required: false,
            default: 1001
        }
    },
    perform: (request, { payload, settings }) => {
        if (!payload.email && !payload.userId) {
            throw new actions_core_1.PayloadValidationError('Must include email or userId.');
        }
        const updateUserRequestPayload = transformIterableUserPayload(payload);
        const endpoint = (0, utils_1.getRegionalEndpoint)('updateUser', settings.dataCenterLocation);
        return request(endpoint, {
            method: 'post',
            json: updateUserRequestPayload,
            timeout: Math.max(30000, actions_core_1.DEFAULT_REQUEST_TIMEOUT)
        });
    },
    performBatch: (request, { settings, payload }) => {
        const bulkUpdateUserRequestPayload = {
            users: payload.map(transformIterableUserPayload)
        };
        const endpoint = (0, utils_1.getRegionalEndpoint)('bulkUpdateUser', settings.dataCenterLocation);
        return request(endpoint, {
            method: 'post',
            json: bulkUpdateUserRequestPayload,
            timeout: Math.max(30000, actions_core_1.DEFAULT_REQUEST_TIMEOUT)
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map