"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = validate;
exports.cleanEventName = cleanEventName;
const actions_core_1 = require("@segment/actions-core");
function validate(payload) {
    if (payload.record_details.object_type !== 'contact' && typeof payload.record_details.object_id !== 'number') {
        throw new actions_core_1.PayloadValidationError('object_id is required and must be numeric');
    }
    if (payload.record_details.object_type === 'contact' &&
        typeof payload.record_details.object_id !== 'number' &&
        !payload.record_details.email &&
        !payload.record_details.utk) {
        throw new actions_core_1.PayloadValidationError('Contact requires at least one of object_id (as number), email or utk to be provided');
    }
    cleanIdentifiers(payload);
    payload.event_name = cleanEventName(payload.event_name);
    payload.properties = cleanPropObj(payload.properties ?? {});
    return payload;
}
function cleanIdentifiers(payload) {
    if (payload.record_details.email && payload.record_details.object_type !== 'contact') {
        delete payload.record_details.email;
    }
    if (payload.record_details.utk && payload.record_details.object_type !== 'contact') {
        delete payload.record_details.utk;
    }
}
function cleanEventName(str) {
    return str
        .toLowerCase()
        .replace(/[^a-z0-9_-]/g, '_')
        .trim();
}
function cleanPropObj(obj) {
    const cleanObj = {};
    if (obj === undefined) {
        return undefined;
    }
    Object.keys(obj).forEach((key) => {
        const value = obj[key];
        const cleanKey = cleanProp(key);
        if (typeof value === 'boolean' || typeof value === 'number') {
            cleanObj[cleanKey] = value;
        }
        else if (typeof value === 'string' &&
            (value.toLowerCase().trim() === 'true' || value.toLowerCase().trim() === 'false')) {
            cleanObj[cleanKey] = value.toLowerCase().trim() === 'true';
        }
        else if (!isNaN(Number(value))) {
            cleanObj[cleanKey] = Number(value);
        }
        else if (typeof value === 'object' && value !== null) {
            cleanObj[cleanKey] = JSON.stringify(value).trim();
        }
        else {
            cleanObj[cleanKey] = String(value).trim();
        }
    });
    return cleanObj;
}
function cleanProp(str) {
    str = str.toLowerCase().replace(/[^a-z0-9_]/g, '_');
    if (!/^[a-z]/.test(str)) {
        throw new actions_core_1.PayloadValidationError(`Property ${str} in event has an invalid name. Property names must start with a letter.`);
    }
    return str;
}
//# sourceMappingURL=validation-functions.js.map