"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadLogMethods = loadLogMethods;
var axios_1 = require("axios");
var url_1 = require("url");
var log_method_latency_collection_1 = require("../collections/log-method-latency.collection");
var log_subscription_collection_1 = require("../collections/log-subscription.collection");
var log_collection_1 = require("../collections/log.collection");
var resolveio_server_app_1 = require("../resolveio-server-app");
var common_1 = require("../util/common");
var error_reporter_1 = require("../util/error-reporter");
var error_tracking_1 = require("../util/error-tracking");
var DEFAULT_RESOLVEIO_LOGS_ENDPOINT = 'https://backend.resolveio.com/api/logs/query';
var MAX_LOG_QUERY_LIMIT = 5000;
var DEFAULT_LOG_QUERY_LIMIT = 250;
var REMOTE_LOG_QUERY_TIMEOUT_MS = 20000;
function normalizeString(value) {
    if (value === undefined || value === null) {
        return '';
    }
    return String(value).trim();
}
function normalizeLogsSourceMode(value) {
    var mode = normalizeString(value).toLowerCase();
    if (mode === 'local' || mode === 'remote' || mode === 'resolveio' || mode === 'aicoder' || mode === 'auto') {
        return mode;
    }
    return 'auto';
}
function toSafeInteger(value, fallback) {
    var parsed = Number(value);
    if (!Number.isFinite(parsed)) {
        return fallback;
    }
    return Math.floor(parsed);
}
function looksLikeResolveIOHost(serverConfig) {
    var e_1, _a;
    var candidates = [
        serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.ROOT_URL,
        serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.SERVER_URL
    ];
    try {
        for (var candidates_1 = __values(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
            var candidate = candidates_1_1.value;
            var url = normalizeString(candidate);
            if (!url) {
                continue;
            }
            try {
                var parsed = new url_1.URL(url.includes('://') ? url : "https://".concat(url));
                var host = normalizeString(parsed.hostname).toLowerCase();
                if (host === 'backend.resolveio.com' || host === 'resolveio.com' || host.endsWith('.resolveio.com')) {
                    return true;
                }
            }
            catch (_b) {
                var host = url.toLowerCase();
                if (host.includes('backend.resolveio.com') || host.includes('resolveio.com')) {
                    return true;
                }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (candidates_1_1 && !candidates_1_1.done && (_a = candidates_1.return)) _a.call(candidates_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return false;
}
function resolveLogsSourceMode(serverConfig, forcedMode) {
    var forced = normalizeLogsSourceMode(forcedMode);
    if (forced !== 'auto') {
        return forced;
    }
    var configured = normalizeLogsSourceMode(process.env.LOGS_DATA_MODE
        || process.env.RESOLVEIO_LOGS_MODE
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.LOGS_DATA_MODE)
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.RESOLVEIO_LOGS_MODE)
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.AI_ASSISTANT_MODE)
        || process.env.AI_ASSISTANT_MODE);
    if (configured !== 'auto') {
        return configured;
    }
    return 'resolveio';
}
function shouldUseRemoteLogsSource(serverConfig, forcedMode) {
    var mode = resolveLogsSourceMode(serverConfig, forcedMode);
    if (mode === 'remote') {
        return true;
    }
    if (mode === 'local' || mode === 'aicoder') {
        return false;
    }
    if (mode === 'resolveio') {
        return !looksLikeResolveIOHost(serverConfig);
    }
    return false;
}
function normalizeLogQueryPayload(payload) {
    var raw = (payload && typeof payload === 'object') ? payload : {};
    var query = (raw.query && typeof raw.query === 'object') ? raw.query : {};
    var optionsRaw = (raw.options && typeof raw.options === 'object') ? raw.options : {};
    var limit = Math.max(1, Math.min(MAX_LOG_QUERY_LIMIT, toSafeInteger(optionsRaw.limit, DEFAULT_LOG_QUERY_LIMIT)));
    var skip = Math.max(0, toSafeInteger(optionsRaw.skip, 0));
    var sort = (optionsRaw.sort && typeof optionsRaw.sort === 'object') ? optionsRaw.sort : { createdAt: -1 };
    var projection = (optionsRaw.projection && typeof optionsRaw.projection === 'object')
        ? optionsRaw.projection
        : ((optionsRaw.fields && typeof optionsRaw.fields === 'object') ? optionsRaw.fields : undefined);
    var includeCount = raw.include_count !== false && raw.includeCount !== false;
    var sourceMode = normalizeLogsSourceMode(raw.force_source || raw.source_mode || raw.mode);
    return {
        query: query,
        options: __assign({ sort: sort, limit: limit, skip: skip }, (projection ? { projection: projection } : {})),
        includeCount: includeCount,
        sourceMode: sourceMode
    };
}
function resolveRemoteLogsEndpoint(serverConfig) {
    var endpoint = normalizeString(process.env.RESOLVEIO_LOGS_ENDPOINT
        || process.env.REMOTE_LOGS_ENDPOINT
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.RESOLVEIO_LOGS_ENDPOINT)
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.REMOTE_LOGS_ENDPOINT));
    return endpoint || DEFAULT_RESOLVEIO_LOGS_ENDPOINT;
}
function resolveRemoteLogsApiKey(serverConfig) {
    return normalizeString(process.env.RESOLVEIO_LOGS_API_KEY
        || process.env.REMOTE_LOGS_API_KEY
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.RESOLVEIO_LOGS_API_KEY)
        || (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.REMOTE_LOGS_API_KEY));
}
function reviveIsoDateStrings(value) {
    if (Array.isArray(value)) {
        return value.map(function (entry) { return reviveIsoDateStrings(entry); });
    }
    if (!value || typeof value !== 'object') {
        if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value)) {
            var parsed = new Date(value);
            if (!Number.isNaN(parsed.getTime())) {
                return parsed;
            }
        }
        return value;
    }
    var next = {};
    Object.keys(value).forEach(function (key) {
        next[key] = reviveIsoDateStrings(value[key]);
    });
    return next;
}
function runLocalLogsQuery(query, options, includeCount) {
    return __awaiter(this, void 0, void 0, function () {
        var logs, count, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, log_collection_1.Logs.find(query, options)];
                case 1:
                    logs = _b.sent();
                    if (!includeCount) return [3 /*break*/, 3];
                    return [4 /*yield*/, log_collection_1.Logs.countDocuments(query)];
                case 2:
                    _a = _b.sent();
                    return [3 /*break*/, 4];
                case 3:
                    _a = logs.length;
                    _b.label = 4;
                case 4:
                    count = _a;
                    return [2 /*return*/, {
                            source: 'local',
                            logs: logs,
                            count: count
                        }];
            }
        });
    });
}
function runRemoteLogsQuery(serverConfig, payload) {
    return __awaiter(this, void 0, void 0, function () {
        var endpoint, apiKey, response, result;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    endpoint = resolveRemoteLogsEndpoint(serverConfig);
                    apiKey = resolveRemoteLogsApiKey(serverConfig);
                    if (!apiKey) {
                        throw new Error('Missing RESOLVEIO_LOGS_API_KEY for remote log query.');
                    }
                    return [4 /*yield*/, axios_1.default.post(endpoint, {
                            query: payload.query,
                            options: payload.options,
                            include_count: payload.includeCount
                        }, {
                            headers: {
                                'Content-Type': 'application/json',
                                'x-resolveio-logs-key': apiKey
                            },
                            timeout: REMOTE_LOG_QUERY_TIMEOUT_MS
                        })];
                case 1:
                    response = _b.sent();
                    result = ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.result) || {};
                    return [2 /*return*/, {
                            source: 'remote',
                            logs: Array.isArray(result.logs) ? reviveIsoDateStrings(result.logs) : [],
                            count: Number.isFinite(Number(result.count)) ? Number(result.count) : 0,
                            endpoint: endpoint
                        }];
            }
        });
    });
}
function loadLogMethods(methodManager) {
    methodManager.methods({
        insertErrorLog: {
            function: function (message, data) {
                return __awaiter(this, void 0, void 0, function () {
                    var payloadCorrelationId, correlationId, payload;
                    var _a, _b, _c;
                    return __generator(this, function (_d) {
                        switch (_d.label) {
                            case 0:
                                payloadCorrelationId = typeof data === 'object' && data
                                    ? (typeof data.correlationId === 'string' && data.correlationId)
                                        || (typeof data.error === 'object' && data.error && typeof data.error.correlationId === 'string' && data.error.correlationId)
                                    : undefined;
                                correlationId = (0, error_tracking_1.getCorrelationId)() || payloadCorrelationId || (0, common_1.objectIdHexString)();
                                payload = {
                                    user: this.user,
                                    id_user: this.id_user,
                                    message: message,
                                    data: data,
                                    correlationId: correlationId
                                };
                                return [4 /*yield*/, error_reporter_1.ErrorReporter.report({
                                        sourceApp: 'method-logs',
                                        message: 'Error Detected - ' + resolveio_server_app_1.ResolveIOServer.getClientName(),
                                        environment: ((_a = this.serverConfig) === null || _a === void 0 ? void 0 : _a.ROOT_URL) || ((_b = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _b === void 0 ? void 0 : _b.ROOT_URL),
                                        clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
                                        clientName: (_c = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _c === void 0 ? void 0 : _c.CLIENT_NAME,
                                        severity: 'error',
                                        context: payload,
                                        metadata: {
                                            context: 'insertErrorLog',
                                            message: message,
                                            correlationId: correlationId
                                        },
                                        correlationId: correlationId
                                    })];
                            case 1:
                                _d.sent();
                                if (!resolveio_server_app_1.ResolveIOServer.shouldWriteLogsOffline()) return [3 /*break*/, 2];
                                resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({
                                    type: 'log',
                                    data: {
                                        _id: (0, common_1.objectIdHexString)(),
                                        createdAt: new Date(),
                                        type: 'error',
                                        collection: '',
                                        id_document: '',
                                        payload: JSON.stringify([payload], null, 2),
                                        method: '',
                                        id_user: this.id_user || '',
                                        user: this.user || '',
                                        messageId: 0,
                                        route: '',
                                        instance_index: process.env.NODE_APP_INSTANCE || '0',
                                        correlationId: correlationId
                                    }
                                });
                                return [3 /*break*/, 4];
                            case 2: return [4 /*yield*/, log_collection_1.Logs.insertOne({
                                    _id: (0, common_1.objectIdHexString)(),
                                    type: 'error',
                                    collection: '',
                                    id_document: '',
                                    payload: JSON.stringify([payload], null, 2),
                                    method: '',
                                    id_user: this.id_user || '',
                                    user: this.user || '',
                                    messageId: 0,
                                    route: '',
                                    client: 'ResolveIO',
                                    instance: resolveio_server_app_1.ResolveIOServer.getInstanceHost(),
                                    instance_index: process.env.NODE_APP_INSTANCE || '0',
                                    correlationId: correlationId
                                })];
                            case 3:
                                _d.sent();
                                _d.label = 4;
                            case 4: return [2 /*return*/, true];
                        }
                    });
                });
            },
            skipValidation: true
        },
        insertSubscriptionLog: {
            bypassLogs: true,
            function: function (type, subscription, collection_name, subData) {
                return __awaiter(this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!resolveio_server_app_1.ResolveIOServer.shouldWriteLogsOffline()) return [3 /*break*/, 1];
                                resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({
                                    type: 'log-subscription',
                                    data: {
                                        _id: (0, common_1.objectIdHexString)(),
                                        __v: 0,
                                        date: new Date(),
                                        type: type,
                                        subscription: subscription,
                                        collection_name: collection_name,
                                        subData: subData,
                                        instance_index: process.env.NODE_APP_INSTANCE || '0'
                                    }
                                });
                                return [3 /*break*/, 3];
                            case 1: return [4 /*yield*/, log_subscription_collection_1.LogSubscriptions.create({
                                    _id: (0, common_1.objectIdHexString)(),
                                    __v: 0,
                                    date: new Date(),
                                    type: type,
                                    subscription: subscription,
                                    collection_name: collection_name,
                                    subData: subData,
                                    client: 'ResolveIO',
                                    instance: resolveio_server_app_1.ResolveIOServer.getInstanceHost()
                                })];
                            case 2:
                                _a.sent();
                                _a.label = 3;
                            case 3: return [2 /*return*/, true];
                        }
                    });
                });
            },
            skipValidation: true
        },
        queryLogsForDashboard: {
            function: function () {
                return __awaiter(this, arguments, void 0, function (payload) {
                    var normalized, useRemote, remote, error_1, fallback, local;
                    if (payload === void 0) { payload = {}; }
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                normalized = normalizeLogQueryPayload(payload);
                                useRemote = shouldUseRemoteLogsSource(this.serverConfig || {}, normalized.sourceMode);
                                if (!useRemote) return [3 /*break*/, 5];
                                _a.label = 1;
                            case 1:
                                _a.trys.push([1, 3, , 5]);
                                return [4 /*yield*/, runRemoteLogsQuery(this.serverConfig || {}, normalized)];
                            case 2:
                                remote = _a.sent();
                                return [2 /*return*/, {
                                        source: remote.source,
                                        logs: remote.logs,
                                        count: remote.count,
                                        endpoint: remote.endpoint
                                    }];
                            case 3:
                                error_1 = _a.sent();
                                return [4 /*yield*/, runLocalLogsQuery(normalized.query, normalized.options, normalized.includeCount)];
                            case 4:
                                fallback = _a.sent();
                                return [2 /*return*/, {
                                        source: fallback.source,
                                        logs: fallback.logs,
                                        count: fallback.count,
                                        remote_error: (error_1 === null || error_1 === void 0 ? void 0 : error_1.message) || String(error_1)
                                    }];
                            case 5: return [4 /*yield*/, runLocalLogsQuery(normalized.query, normalized.options, normalized.includeCount)];
                            case 6:
                                local = _a.sent();
                                return [2 /*return*/, {
                                        source: local.source,
                                        logs: local.logs,
                                        count: local.count
                                    }];
                        }
                    });
                });
            },
            skipValidation: true
        },
        queryResolveIOLogsRemote: {
            function: function () {
                return __awaiter(this, arguments, void 0, function (payload) {
                    var normalized, remote;
                    if (payload === void 0) { payload = {}; }
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                normalized = normalizeLogQueryPayload(__assign(__assign({}, (payload || {})), { force_source: 'remote' }));
                                return [4 /*yield*/, runRemoteLogsQuery(this.serverConfig || {}, normalized)];
                            case 1:
                                remote = _a.sent();
                                return [2 /*return*/, {
                                        source: remote.source,
                                        logs: remote.logs,
                                        count: remote.count,
                                        endpoint: remote.endpoint
                                    }];
                        }
                    });
                });
            },
            skipValidation: true
        },
        superadminAPM: {
            function: function (date_start, date_end, graphInterval) {
                return __awaiter(this, void 0, void 0, function () {
                    var latencies, subscriptions, groupId, groupSort, methodGraphData, subGraphData;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, log_method_latency_collection_1.LogMethodLatencies.aggregate([
                                    {
                                        $match: {
                                            $and: [
                                                {
                                                    createdAt: { $gte: date_start }
                                                },
                                                {
                                                    createdAt: { $lte: date_end }
                                                }
                                            ]
                                        }
                                    },
                                    {
                                        $group: {
                                            _id: '$method',
                                            method: { $first: '$method' },
                                            count: { $sum: 1 },
                                            latency_min: { $min: '$latency_ms' },
                                            latency_avg: { $avg: '$latency_ms' },
                                            latency_max: { $max: '$latency_ms' }
                                        }
                                    }
                                ], { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
                            case 1:
                                latencies = _a.sent();
                                return [4 /*yield*/, log_subscription_collection_1.LogSubscriptions.aggregate([
                                        {
                                            $match: {
                                                $and: [
                                                    {
                                                        createdAt: { $gte: date_start }
                                                    },
                                                    {
                                                        createdAt: { $lte: date_end }
                                                    }
                                                ]
                                            }
                                        },
                                        {
                                            $group: {
                                                _id: '$subscription',
                                                subscription: { $first: '$subscription' },
                                                count: { $sum: 1 }
                                            }
                                        }
                                    ], { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
                            case 2:
                                subscriptions = _a.sent();
                                groupId = {};
                                groupSort = {};
                                if (graphInterval === 'seconds') {
                                    groupId = {
                                        second: {
                                            $second: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        minute: {
                                            $minute: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        hour: {
                                            $hour: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        day: {
                                            $dayOfMonth: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        month: {
                                            $month: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        year: {
                                            $year: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        }
                                    };
                                    groupSort = {
                                        '_id.year': 1,
                                        '_id.month': 1,
                                        '_id.day': 1,
                                        '_id.hour': 1,
                                        '_id.minute': 1,
                                        '_id.second': 1
                                    };
                                }
                                else if (graphInterval === 'minutes') {
                                    groupId = {
                                        minute: {
                                            $minute: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        hour: {
                                            $hour: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        day: {
                                            $dayOfMonth: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        month: {
                                            $month: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        year: {
                                            $year: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        }
                                    };
                                    groupSort = {
                                        '_id.year': 1,
                                        '_id.month': 1,
                                        '_id.day': 1,
                                        '_id.hour': 1,
                                        '_id.minute': 1
                                    };
                                }
                                else if (graphInterval === 'hours') {
                                    groupId = {
                                        hour: {
                                            $hour: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        day: {
                                            $dayOfMonth: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        month: {
                                            $month: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        year: {
                                            $year: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        }
                                    };
                                    groupSort = {
                                        '_id.year': 1,
                                        '_id.month': 1,
                                        '_id.day': 1,
                                        '_id.hour': 1
                                    };
                                }
                                else {
                                    groupId = {
                                        day: {
                                            $dayOfMonth: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        month: {
                                            $month: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        },
                                        year: {
                                            $year: {
                                                date: '$createdAt',
                                                timezone: process.env.TZ_CLIENT || 'America/Chicago'
                                            }
                                        }
                                    };
                                    groupSort = {
                                        '_id.year': 1,
                                        '_id.month': 1,
                                        '_id.day': 1
                                    };
                                }
                                return [4 /*yield*/, log_method_latency_collection_1.LogMethodLatencies.aggregate([
                                        {
                                            $match: {
                                                $and: [
                                                    {
                                                        createdAt: { $gte: date_start }
                                                    },
                                                    {
                                                        createdAt: { $lte: date_end }
                                                    }
                                                ]
                                            }
                                        },
                                        {
                                            $group: {
                                                _id: groupId,
                                                count: {
                                                    $sum: 1
                                                }
                                            }
                                        },
                                        {
                                            $sort: groupSort
                                        }
                                    ], { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
                            case 3:
                                methodGraphData = _a.sent();
                                return [4 /*yield*/, log_subscription_collection_1.LogSubscriptions.aggregate([
                                        {
                                            $match: {
                                                $and: [
                                                    {
                                                        createdAt: { $gte: date_start }
                                                    },
                                                    {
                                                        createdAt: { $lte: date_end }
                                                    }
                                                ]
                                            }
                                        },
                                        {
                                            $group: {
                                                _id: groupId,
                                                count: {
                                                    $sum: 1
                                                }
                                            }
                                        },
                                        {
                                            $sort: groupSort
                                        }
                                    ], { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
                            case 4:
                                subGraphData = _a.sent();
                                return [2 /*return*/, {
                                        methods: latencies,
                                        subscriptions: subscriptions,
                                        methodGraphData: methodGraphData,
                                        subGraphData: subGraphData
                                    }];
                        }
                    });
                });
            },
            skipValidation: true
        }
    });
}

//# sourceMappingURL=logs.js.map
