"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 utils_1 = require("../common/utils");
const functions_1 = require("../trackEvent/functions");
const mixpanel_properties_1 = require("../mixpanel-properties");
const dayjs_1 = __importDefault(require("../../../lib/dayjs"));
const topLevelKeys = [
    'affiliation',
    'subtotal',
    'total',
    'revenue',
    'shipping',
    'tax',
    'discount',
    'coupon',
    'currency',
    'order_number',
    'products'
];
const getPurchaseEventsFromPayload = (payload, settings) => {
    const orderCompletedEvent = {
        event: payload.event,
        properties: {
            ...(0, functions_1.getEventProperties)(payload, settings)
        }
    };
    let purchaseEvents = [];
    if (payload.products && payload.generatePurchaseEventPerProduct) {
        const datetime = payload.time;
        let time = datetime && dayjs_1.default.utc(datetime).isValid() ? dayjs_1.default.utc(datetime).valueOf() : Date.now();
        const insertId = payload.insert_id ?? (0, utils_1.cheapGuid)();
        let insertIdCount = 0;
        purchaseEvents = payload.products.map((product) => {
            return {
                event: 'Product Purchased',
                properties: {
                    ...(0, actions_core_1.omit)(orderCompletedEvent.properties, topLevelKeys),
                    $insert_id: (insertIdCount++).toString() + insertId,
                    time: --time,
                    ...product
                }
            };
        });
    }
    return [orderCompletedEvent, ...purchaseEvents];
};
const processData = async (request, settings, payload, features) => {
    const events = [];
    const sentEvents = [];
    payload.forEach((value) => {
        const purchaseEvents = getPurchaseEventsFromPayload(value, settings).flat();
        sentEvents.push(purchaseEvents);
        events.push(...purchaseEvents);
        return purchaseEvents;
    });
    const throwHttpErrors = features && features['mixpanel-multistatus'] ? false : true;
    const response = await callMixpanelApi(request, settings, events, throwHttpErrors);
    if (features && features['mixpanel-multistatus']) {
        return (0, utils_1.handleMixPanelApiResponse)(payload.length, response, sentEvents);
    }
    return response;
};
const callMixpanelApi = async (request, settings, events, throwHttpErrors) => {
    return await request(`${(0, utils_1.getApiServerUrl)(settings.apiRegion)}/import?strict=${settings.strictMode ?? `1`}`, {
        method: 'post',
        json: events,
        headers: {
            authorization: `Basic ${Buffer.from(`${settings.apiSecret}:`).toString('base64')}`
        },
        throwHttpErrors: throwHttpErrors
    });
};
const action = {
    title: 'Track Purchase',
    description: "Send an 'Order Completed' Event to Mixpanel.",
    defaultSubscription: 'type = "track"',
    fields: {
        generatePurchaseEventPerProduct: {
            label: 'Generate Purchase Event Per Product',
            description: 'When enabled, send "Product Purchased" with each product within the event.',
            type: 'boolean',
            default: true
        },
        ...mixpanel_properties_1.eventProperties,
        ...mixpanel_properties_1.productsProperties,
        event: {
            label: 'Event Name',
            type: 'string',
            description: 'The name of the action being performed.',
            required: true,
            default: {
                '@path': '$.event'
            }
        }
    },
    perform: async (request, { settings, payload, features }) => {
        return processData(request, settings, [payload], features);
    },
    performBatch: async (request, { settings, payload, features }) => {
        return processData(request, settings, payload, features);
    }
};
exports.default = action;
//# sourceMappingURL=index.js.map