"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 action = {
    title: 'Cart Updates',
    description: 'Updates the shoppingCartItems field on the user profile.',
    defaultSubscription: 'type = "track" and event == "Cart Updated"',
    fields: {
        user: {
            label: 'User Data',
            description: 'Updates user data or adds a user if none exists',
            type: 'object',
            required: true,
            additionalProperties: false,
            defaultObjectUI: 'keyvalue:only',
            default: {
                email: {
                    '@if': {
                        exists: { '@path': '$.properties.email' },
                        then: { '@path': '$.properties.email' },
                        else: { '@path': '$.context.traits.email' }
                    }
                },
                userId: { '@path': '$.userId' },
                dataFields: { '@path': '$.context.traits' },
                phoneNumber: { '@path': '$.context.traits.phone' },
                mergeNestedObjects: false
            },
            properties: {
                email: {
                    ...shared_fields_1.EMAIL_FIELD
                },
                userId: {
                    ...shared_fields_1.USER_ID_FIELD
                },
                mergeNestedObjects: {
                    ...shared_fields_1.MERGE_NESTED_OBJECTS_FIELD
                },
                dataFields: {
                    ...shared_fields_1.USER_DATA_FIELDS
                },
                phoneNumber: {
                    ...shared_fields_1.USER_PHONE_NUMBER_FIELD
                }
            }
        },
        items: {
            ...shared_fields_1.ITEMS_FIELD
        }
    },
    perform: (request, { payload, settings }) => {
        const { user, items } = payload;
        if (!user.email && !user.userId) {
            throw new actions_core_1.PayloadValidationError('Must include email or userId.');
        }
        const phoneNumber = user.phoneNumber;
        delete user.phoneNumber;
        const formattedDataFields = (0, utils_1.convertDatesInObject)(user.dataFields ?? {});
        const updateCartRequest = {
            user: {
                ...user,
                dataFields: {
                    ...formattedDataFields,
                    phoneNumber: phoneNumber
                }
            },
            items: (0, utils_1.transformItems)(items)
        };
        const endpoint = (0, utils_1.getRegionalEndpoint)('updateCart', settings.dataCenterLocation);
        return request(endpoint, {
            method: 'post',
            json: updateCartRequest,
            timeout: Math.max(30000, actions_core_1.DEFAULT_REQUEST_TIMEOUT)
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map