"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cache = void 0;
exports.getSchemaFromCache = getSchemaFromCache;
exports.saveSchemaToCache = saveSchemaToCache;
exports.compareSchemas = compareSchemas;
const actions_core_1 = require("@segment/actions-core");
const lru_cache_1 = require("lru-cache");
exports.cache = new lru_cache_1.LRUCache({
    max: 2000,
    ttl: 1000 * 60 * 60
});
function getKey(name, subscriptionMetadata) {
    return `${subscriptionMetadata.actionConfigId}-${name}`;
}
function getSchemaFromCache(name, subscriptionMetadata, statsContext) {
    if (!subscriptionMetadata || !subscriptionMetadata?.actionConfigId) {
        statsContext?.statsClient?.incr('cache.get.error', 1, statsContext?.tags);
        return undefined;
    }
    const schema = exports.cache.get(getKey(name, subscriptionMetadata)) ?? undefined;
    return schema;
}
async function saveSchemaToCache(schema, subscriptionMetadata, statsContext) {
    if (!subscriptionMetadata || !subscriptionMetadata?.actionConfigId) {
        statsContext?.statsClient?.incr('cache.save.error', 1, statsContext?.tags);
        return;
    }
    exports.cache.set(getKey(schema.name, subscriptionMetadata), schema);
    statsContext?.statsClient?.incr('cache.save.success', 1, statsContext?.tags);
}
function compareSchemas(schema1, schema2) {
    if (schema2 === undefined) {
        return { match: 'no_match', missingProperties: {} };
    }
    if (schema1.name !== schema2.name && schema1.name !== schema2.fullyQualifiedName) {
        throw new actions_core_1.PayloadValidationError("Hubspot.CustomEvent.compareSchemas: Schema names don't match");
    }
    const missingProperties = {};
    for (const [key, prop1] of Object.entries(schema1.properties)) {
        const prop2 = schema2.properties[key];
        if (prop2 === undefined) {
            missingProperties[key] = prop1;
            continue;
        }
        if (prop1.stringFormat === prop2.stringFormat && prop1.type === prop2.type) {
            continue;
        }
        else {
            throw new actions_core_1.PayloadValidationError("Hubspot.CustomEvent.compareSchemas: Schema property types don't match");
        }
    }
    return {
        match: Object.keys(missingProperties).length > 0 ? 'properties_missing' : 'full_match',
        missingProperties
    };
}
//# sourceMappingURL=cache-functions.js.map