"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isIsoDate = exports.sendSingle = exports.sendBatch = exports.resolveIdentifiers = exports.buildPayload = exports.convertAttributeTimestamps = exports.convertValidTimestamp = exports.AccountRegion = exports.trackApiEndpoint = void 0;
const dayjs_1 = __importDefault(require("../../lib/dayjs"));
const isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
const formats_1 = require("ajv-formats/dist/formats");
const isEmail = (value) => {
    return formats_1.fullFormats.email.test(value);
};
const isRecord = (value) => {
    return (0, isPlainObject_1.default)(value);
};
const isIsoDate = (value) => {
    const isoformat = '^\\d{4}-\\d{2}-\\d{2}' +
        '((T\\d{2}:\\d{2}(:\\d{2})?)' +
        '(\\.\\d{1,9})?' +
        '(Z|(\\+|-)\\d{2}:?\\d{2})?)?$';
    const matcher = new RegExp(isoformat);
    return typeof value === 'string' && matcher.test(value) && !isNaN(Date.parse(value));
};
exports.isIsoDate = isIsoDate;
const trackApiEndpoint = ({ accountRegion }) => {
    if (accountRegion === AccountRegion.EU) {
        return 'https://track-eu.customer.io';
    }
    return 'https://track.customer.io';
};
exports.trackApiEndpoint = trackApiEndpoint;
var AccountRegion;
(function (AccountRegion) {
    AccountRegion["US"] = "US \uD83C\uDDFA\uD83C\uDDF8";
    AccountRegion["EU"] = "EU \uD83C\uDDEA\uD83C\uDDFA";
})(AccountRegion || (exports.AccountRegion = AccountRegion = {}));
const convertValidTimestamp = (value) => {
    if (typeof value !== 'string' || /^\d+$/.test(value)) {
        return value;
    }
    const maybeDate = dayjs_1.default.utc(value);
    if (maybeDate.isValid()) {
        return maybeDate.unix();
    }
    return value;
};
exports.convertValidTimestamp = convertValidTimestamp;
const convertAttributeTimestamps = (payload) => {
    const clone = {};
    const keys = Object.keys(payload);
    keys.forEach((k) => {
        const key = k;
        const value = payload[key];
        if (typeof value === 'string') {
            const maybeDate = (0, dayjs_1.default)(value);
            if (isIsoDate(value)) {
                ;
                clone[key] = maybeDate.unix();
                return;
            }
        }
        if (isRecord(value)) {
            clone[key] = (0, exports.convertAttributeTimestamps)(value);
            return;
        }
        clone[key] = value;
    });
    return clone;
};
exports.convertAttributeTimestamps = convertAttributeTimestamps;
const buildPayload = ({ action, type, payload }) => {
    const { convert_timestamp, person_id, anonymous_id, email, object_id, object_type_id, timestamp, ...data } = payload;
    let rest = data;
    if ('enable_batching' in rest) {
        delete rest.enable_batching;
    }
    if ('batch_size' in rest) {
        delete rest.batch_size;
    }
    if ('convert_timestamp' in payload && convert_timestamp !== false) {
        rest = (0, exports.convertAttributeTimestamps)(rest);
    }
    if ('timestamp' in payload && timestamp) {
        rest = { ...rest, timestamp: (0, exports.convertValidTimestamp)(timestamp) };
    }
    const body = {
        type,
        action,
        ...rest
    };
    if (anonymous_id) {
        body.attributes = { ...body.attributes, anonymous_id: anonymous_id };
    }
    if (action !== 'merge') {
        body.identifiers = (0, exports.resolveIdentifiers)({ anonymous_id, email, object_id, object_type_id, person_id });
    }
    if (body.identifiers && 'anonymous_id' in body.identifiers) {
        delete body.attributes?.anonymous_id;
    }
    return body;
};
exports.buildPayload = buildPayload;
const resolveIdentifiers = ({ anonymous_id, email, object_id, object_type_id = '1', person_id }) => {
    if (object_id && object_type_id) {
        return {
            object_id: object_id,
            object_type_id: object_type_id
        };
    }
    else if (person_id?.startsWith('cio_')) {
        return { cio_id: person_id.slice(4) };
    }
    else if (isEmail(person_id)) {
        return { email: person_id };
    }
    else if (person_id) {
        return { id: person_id };
    }
    else if (email) {
        return { email: email };
    }
    else if (anonymous_id) {
        return { anonymous_id: anonymous_id };
    }
};
exports.resolveIdentifiers = resolveIdentifiers;
const sendBatch = (request, options) => {
    if (!options?.length) {
        return;
    }
    const [{ settings }] = options;
    const batch = options.map((opts) => (0, exports.buildPayload)(opts));
    return request(`${(0, exports.trackApiEndpoint)(settings)}/api/v2/batch`, {
        method: 'post',
        json: {
            batch
        }
    });
};
exports.sendBatch = sendBatch;
const sendSingle = (request, options) => {
    const json = (0, exports.buildPayload)(options);
    return request(`${(0, exports.trackApiEndpoint)(options.settings)}/api/v2/entity`, {
        method: 'post',
        json
    });
};
exports.sendSingle = sendSingle;
//# sourceMappingURL=utils.js.map