"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlowQueryReporter = void 0;
var crypto_1 = require("crypto");
var os_1 = require("os");
var resolveio_server_app_1 = require("../resolveio-server-app");
var common_1 = require("./common");
var DEFAULT_SLOW_QUERY_THRESHOLD_MS = 1000;
var SlowQueryReporter = /** @class */ (function () {
    function SlowQueryReporter() {
    }
    SlowQueryReporter.reportSlowQuery = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var thresholdMs, manager, queryHash, payload, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.isReportingEnabled()) {
                            return [2 /*return*/];
                        }
                        thresholdMs = this.getThresholdMs();
                        if (thresholdMs <= 0 || params.durationMs < thresholdMs) {
                            return [2 /*return*/];
                        }
                        manager = resolveio_server_app_1.ResolveIOServer['SlowQueryManager'];
                        if (!manager || typeof manager.ingestSlowQuery !== 'function') {
                            console.error('SlowQueryReporter skipped: local SlowQueryManager is not available');
                            return [2 /*return*/];
                        }
                        if (typeof manager.isReady === 'function' && !manager.isReady()) {
                            return [2 /*return*/];
                        }
                        queryHash = params.queryHash || this.generateQueryHash(params);
                        payload = {
                            queryHash: queryHash,
                            collection: params.collection,
                            pipeline: params.pipeline ? (0, common_1.deepCopy)(params.pipeline) : undefined,
                            filter: params.filter ? (0, common_1.deepCopy)(params.filter) : undefined,
                            options: params.options ? (0, common_1.deepCopy)(params.options) : undefined,
                            durationMs: params.durationMs,
                            thresholdMs: thresholdMs,
                            clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
                            clientName: this.getClientName(),
                            sourceApp: params.sourceApp || 'mongo-manager',
                            environment: this.getEnvironment(),
                            nodeHostname: (0, os_1.hostname)(),
                            notes: params.notes,
                            server_url: params.serverUrl || this.getServerUrl(),
                            publication: params.publication,
                            subscription_data: params.subscriptionData,
                            userId: params.userId
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, manager.ingestSlowQuery(payload)];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        err_1 = _a.sent();
                        console.error('SlowQueryReporter failed', err_1);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    SlowQueryReporter.reportSlowQueryFireAndForget = function (params) {
        // eslint-disable-next-line no-restricted-syntax, promise/prefer-await-to-then
        void this.reportSlowQuery(params).catch(function (err) {
            console.error('SlowQueryReporter fire-and-forget error', err);
        });
    };
    SlowQueryReporter.isReportingEnabled = function () {
        var config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
        var envValue = process.env.SLOW_QUERY_ENABLED;
        if (typeof envValue === 'string' && envValue.length) {
            var normalized = envValue.trim().toLowerCase();
            if (['true', '1', 'yes'].includes(normalized)) {
                return true;
            }
            else if (['false', '0', 'no'].includes(normalized)) {
                return false;
            }
        }
        var slowQueryConfig = (config && (config.slowQuery || config.SLOW_QUERY)) || null;
        var configValue = typeof (slowQueryConfig === null || slowQueryConfig === void 0 ? void 0 : slowQueryConfig.enabled) !== 'undefined'
            ? slowQueryConfig.enabled
            : config === null || config === void 0 ? void 0 : config.SLOW_QUERY_ENABLED;
        if (typeof configValue === 'boolean') {
            return configValue;
        }
        if (typeof configValue === 'string' && configValue.length) {
            var normalized = configValue.trim().toLowerCase();
            if (['true', '1', 'yes'].includes(normalized)) {
                return true;
            }
            else if (['false', '0', 'no'].includes(normalized)) {
                return false;
            }
        }
        if (typeof configValue === 'number') {
            return configValue !== 0;
        }
        return true;
    };
    SlowQueryReporter.getThresholdMs = function () {
        var config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
        var envValue = process.env.SLOW_QUERY_THRESHOLD_MS;
        if (envValue && !Number.isNaN(Number(envValue))) {
            return Number.parseInt(envValue, 10);
        }
        var configValue = config === null || config === void 0 ? void 0 : config.SLOW_QUERY_THRESHOLD_MS;
        if (typeof configValue === 'number') {
            return configValue;
        }
        if (typeof configValue === 'string' && configValue.length && !Number.isNaN(Number(configValue))) {
            return Number.parseInt(configValue, 10);
        }
        return DEFAULT_SLOW_QUERY_THRESHOLD_MS;
    };
    SlowQueryReporter.getEnvironment = function () {
        var config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
        return ((config === null || config === void 0 ? void 0 : config.RESOLVEIO_ENV) ||
            (config === null || config === void 0 ? void 0 : config.ENVIRONMENT) ||
            (config === null || config === void 0 ? void 0 : config.ROOT_URL) ||
            process.env.RESOLVEIO_ENV ||
            process.env.NODE_ENV ||
            'unknown');
    };
    SlowQueryReporter.getClientName = function () {
        var config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
        return (config === null || config === void 0 ? void 0 : config.CLIENT_NAME) || resolveio_server_app_1.ResolveIOServer.getClientName();
    };
    SlowQueryReporter.generateQueryHash = function (params) {
        try {
            var normalized = this.normalizeForHash({
                collection: params.collection,
                filter: params.filter || null,
                pipeline: params.pipeline || null,
                options: params.options || null,
                queryType: params.queryType
            });
            var digest = (0, crypto_1.createHash)('sha256').update(JSON.stringify(normalized)).digest('hex').slice(0, 16);
            return "".concat(params.collection, "-").concat(digest);
        }
        catch (err) {
            console.error('SlowQueryReporter hash generation failed', err);
            return "".concat(params.collection, "-").concat(Date.now());
        }
    };
    SlowQueryReporter.getServerUrl = function () {
        var config = resolveio_server_app_1.ResolveIOServer.getServerConfig();
        if (config === null || config === void 0 ? void 0 : config.ROOT_URL) {
            return "".concat(config.ROOT_URL).trim();
        }
        if (process.env.ROOT_URL) {
            return process.env.ROOT_URL.trim();
        }
        return undefined;
    };
    SlowQueryReporter.normalizeForHash = function (value) {
        var _this = this;
        if (value === null || value === undefined) {
            return value;
        }
        if (Array.isArray(value)) {
            return value.map(function (item) { return _this.normalizeForHash(item); });
        }
        if (value instanceof RegExp) {
            return value.toString();
        }
        if (typeof value === 'object') {
            if (typeof value.toHexString === 'function') {
                return value.toHexString();
            }
            var ordered_1 = {};
            Object.keys(value).sort().forEach(function (key) {
                ordered_1[key] = _this.normalizeForHash(value[key]);
            });
            return ordered_1;
        }
        return value;
    };
    return SlowQueryReporter;
}());
exports.SlowQueryReporter = SlowQueryReporter;

//# sourceMappingURL=slow-query-reporter.js.map
