"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 config_1 = require("../config");
const uuid_1 = require("@lukeed/uuid");
const functions_1 = require("../functions");
const properties_1 = require("../properties");
const dayjs_1 = __importDefault(require("dayjs"));
const createEventData = (payload) => ({
    data: {
        type: 'event',
        attributes: {
            properties: { ...payload.properties },
            time: payload.time ? (0, dayjs_1.default)(payload.time).toISOString() : undefined,
            value: payload.value,
            unique_id: payload.unique_id,
            metric: {
                data: {
                    type: 'metric',
                    attributes: {
                        name: payload.event_name ?? 'Order Completed'
                    }
                }
            },
            profile: {
                data: {
                    type: 'profile',
                    attributes: payload.profile
                }
            }
        }
    }
});
const sendProductRequests = async (payload, orderEventData, request) => {
    if (!payload.products || !Array.isArray(payload.products)) {
        return;
    }
    delete orderEventData.data.attributes.properties?.products;
    const productPromises = payload.products.map((product) => {
        const productEventData = {
            data: {
                type: 'event',
                attributes: {
                    properties: { ...orderEventData.data.attributes.properties, ...product },
                    unique_id: (0, uuid_1.v4)(),
                    metric: {
                        data: {
                            type: 'metric',
                            attributes: {
                                name: payload.product_event_name ?? 'Ordered Product'
                            }
                        }
                    },
                    time: orderEventData.data.attributes.time,
                    profile: orderEventData.data.attributes.profile
                }
            }
        };
        return request(`${config_1.API_URL}/events/`, {
            method: 'POST',
            json: productEventData
        });
    });
    await Promise.all(productPromises);
};
const action = {
    title: 'Order Completed',
    description: 'Order Completed Event action tracks users Order Completed events and associate it with their profile.',
    defaultSubscription: 'type = "track"',
    fields: {
        profile: {
            label: 'Profile',
            description: `Properties of the profile that triggered this event.`,
            type: 'object',
            properties: {
                email: {
                    label: 'Email',
                    type: 'string'
                },
                phone_number: {
                    label: 'Phone Number',
                    type: 'string'
                },
                country_code: { ...properties_1.country_code },
                external_id: {
                    label: 'External Id',
                    description: 'A unique identifier used by customers to associate Klaviyo profiles with profiles in an external system.',
                    type: 'string',
                    default: { '@path': '$.userId' }
                },
                anonymous_id: {
                    label: 'Anonymous Id',
                    description: 'Anonymous user identifier for the user.',
                    type: 'string',
                    default: { '@path': '$.anonymousId' }
                }
            },
            additionalProperties: true,
            required: true
        },
        properties: {
            description: `Properties of this event.`,
            label: 'Properties',
            type: 'object',
            default: {
                '@path': '$.properties'
            },
            required: true
        },
        time: {
            label: 'Time',
            description: `When this event occurred. By default, the time the request was received will be used.
      The time is truncated to the second. The time must be after the year 2000 and can only
      be up to 1 year in the future.
      `,
            type: 'datetime',
            default: {
                '@path': '$.timestamp'
            }
        },
        value: {
            label: 'Value',
            description: 'A numeric value to associate with this event. For example, the dollar amount of a purchase.',
            type: 'number'
        },
        unique_id: {
            label: 'Unique ID',
            description: `A unique identifier for an event. If the unique_id is repeated for the same
      profile and metric, only the first processed event will be recorded. If this is not
      present, this will use the time to the second. Using the default, this limits only one
      event per profile per second.
      `,
            type: 'string',
            default: {
                '@path': '$.messageId'
            }
        },
        products: {
            label: 'Products',
            description: 'List of products purchased in the order.',
            multiple: true,
            type: 'object'
        },
        event_name: {
            label: 'Event Name',
            description: 'Name of the event. This will be used as the metric name for order completed event sent to Klaviyo. It must be configured in Klaviyo.',
            default: 'Order Completed',
            type: 'string'
        },
        product_event_name: {
            label: 'Product Event Name',
            description: 'Name of the Product Event. This will be used as the metric name for each ordered product configured in the product list sent to Klaviyo. It must be configured in Klaviyo.',
            default: 'Ordered Product',
            type: 'string'
        }
    },
    perform: async (request, { payload }) => {
        const { email, phone_number: initialPhoneNumber, external_id, anonymous_id, country_code } = payload.profile;
        const phone_number = (0, functions_1.processPhoneNumber)(initialPhoneNumber, country_code);
        payload.profile.phone_number = phone_number;
        delete payload?.profile?.country_code;
        if (!email && !phone_number && !external_id && !anonymous_id) {
            throw new actions_core_1.PayloadValidationError('One of External ID, Anonymous ID, Phone Number or Email is required.');
        }
        const eventData = createEventData(payload);
        const event = await request(`${config_1.API_URL}/events/`, {
            method: 'POST',
            json: eventData
        });
        if (event.status == 202 && Array.isArray(payload.products)) {
            await sendProductRequests(payload, eventData, request);
        }
        return event;
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map