"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiEndpoints = void 0;
exports.convertDatesInObject = convertDatesInObject;
exports.transformItems = transformItems;
exports.getRegionalEndpoint = getRegionalEndpoint;
const actions_core_1 = require("@segment/actions-core");
const isoDateRegExp = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
function dateToIterableDateStringFormat(isoDateStr) {
    if (!isoDateRegExp.test(isoDateStr)) {
        return null;
    }
    const date = new Date(isoDateStr);
    if (date instanceof Date && !isNaN(date.valueOf())) {
        const dateString = date.toISOString().replace('T', ' ').split('.')[0];
        return `${dateString} +00:00`;
    }
    return null;
}
function convertDatesInObject(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return obj;
    }
    for (const prop in obj) {
        const value = obj[prop];
        if (typeof value === 'string' && isoDateRegExp.test(value)) {
            const dateOnlyRegex = /^\d{4}-\d{2}-\d{2}$/;
            if (dateOnlyRegex.test(value)) {
                obj[prop] = value;
            }
            else {
                obj[prop] = dateToIterableDateStringFormat(value);
            }
        }
        else if (value instanceof Date) {
            obj[prop] = dateToIterableDateStringFormat(value.toISOString());
        }
        else if (typeof value === 'object' && value !== null) {
            convertDatesInObject(value);
        }
        else {
            obj[prop] = value;
        }
    }
    return obj;
}
function transformItems(items) {
    const reservedItemKeys = [
        'product_id',
        'id',
        'sku',
        'name',
        'price',
        'quantity',
        'categories',
        'category',
        'url',
        'image_url',
        'imageUrl'
    ];
    return items.map(({ dataFields, categories, ...rest }) => ({
        ...rest,
        dataFields: convertDatesInObject((0, actions_core_1.omit)(rest, reservedItemKeys) || {}),
        ...(categories && { categories: [categories] })
    }));
}
const regionBaseUrls = {
    united_states: 'https://api.iterable.com',
    europe: 'https://api.eu.iterable.com'
};
exports.apiEndpoints = {
    updateUser: '/api/users/update',
    bulkUpdateUser: '/api/users/bulkUpdate',
    trackEvent: '/api/events/track',
    bulkTrackEvent: '/api/events/trackBulk',
    updateCart: '/api/commerce/updateCart',
    trackPurchase: '/api/commerce/trackPurchase',
    getWebhooks: '/api/webhooks'
};
function getRegionalEndpoint(action, dataCenterLocation = 'united_states') {
    const regionBaseUrl = regionBaseUrls[dataCenterLocation] || regionBaseUrls['united_states'];
    const endpoint = exports.apiEndpoints[action];
    return regionBaseUrl + endpoint;
}
//# sourceMappingURL=utils.js.map