"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const dayjs_1 = __importDefault(require("../../../lib/dayjs"));
const shared_fields_1 = require("../shared-fields");
const utils_1 = require("../utils");
const action = {
    title: 'Track Purchase',
    description: 'Tracks a purchase to Iterable',
    defaultSubscription: 'type = "track" and event == "Order Completed"',
    fields: {
        id: {
            label: 'Order ID',
            description: 'Similar to `Event ID` in custom events. Iterable recommends mapping `order_id` or `messageId`. If a purchase exists with that id, the purchase will be updated. If none is specified, a new id will automatically be generated by Iterable',
            type: 'string',
            required: false,
            default: {
                '@path': '$.properties.order_id'
            }
        },
        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
                },
                dataFields: {
                    ...shared_fields_1.USER_DATA_FIELDS
                },
                mergeNestedObjects: {
                    ...shared_fields_1.MERGE_NESTED_OBJECTS_FIELD
                },
                phoneNumber: {
                    ...shared_fields_1.USER_PHONE_NUMBER_FIELD
                }
            }
        },
        dataFields: {
            ...shared_fields_1.EVENT_DATA_FIELDS
        },
        items: {
            ...shared_fields_1.ITEMS_FIELD
        },
        total: {
            label: 'Total',
            description: 'Total order amount.',
            type: 'number',
            required: true,
            default: { '@path': '$.properties.total' }
        },
        createdAt: {
            ...shared_fields_1.CREATED_AT_FIELD
        },
        campaignId: {
            ...shared_fields_1.CAMPAGIN_ID_FIELD
        },
        templateId: {
            ...shared_fields_1.TEMPLATE_ID_FIELD
        }
    },
    perform: (request, { payload, settings }) => {
        const { user, dataFields } = payload;
        if (!user.email && !user.userId) {
            throw new actions_core_1.PayloadValidationError('Must include email or userId.');
        }
        if (dataFields && Object.prototype.hasOwnProperty.call(dataFields, 'products')) {
            delete dataFields.products;
        }
        const phoneNumber = user.phoneNumber;
        delete user.phoneNumber;
        const formattedDataFields = (0, utils_1.convertDatesInObject)(dataFields ?? {});
        const formattedUserDataFields = (0, utils_1.convertDatesInObject)(user.dataFields ?? {});
        const trackPurchaseRequest = {
            ...payload,
            user: {
                ...user,
                dataFields: {
                    ...formattedUserDataFields,
                    phoneNumber: phoneNumber
                }
            },
            items: (0, utils_1.transformItems)(payload.items),
            createdAt: (0, dayjs_1.default)(payload.createdAt).unix(),
            dataFields: formattedDataFields
        };
        const endpoint = (0, utils_1.getRegionalEndpoint)('trackPurchase', settings.dataCenterLocation);
        return request(endpoint, {
            method: 'post',
            json: trackPurchaseRequest,
            timeout: Math.max(30000, actions_core_1.DEFAULT_REQUEST_TIMEOUT)
        });
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map