"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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerDiagnosticManagerDependencies = registerDiagnosticManagerDependencies;
var resolveio_server_app_1 = require("../resolveio-server-app");
var error_auto_fix_manager_1 = require("./error-auto-fix.manager");
var slow_query_manager_1 = require("./slow-query.manager");
var slow_query_verifier_manager_1 = require("./slow-query-verifier.manager");
var indexesEnsured = false;
function resolveMainCollection(collectionName) {
    var mainDb = resolveio_server_app_1.ResolveIOServer.getMainDB();
    if (!mainDb) {
        throw new Error("Cannot resolve collection ".concat(collectionName, " before MongoDB main DB is initialized."));
    }
    return mainDb.collection(collectionName);
}
function createCollectionAdapter(collectionName) {
    var _this = this;
    var collection = resolveMainCollection(collectionName);
    return {
        findOne: function (query, options) {
            if (query === void 0) { query = {}; }
            if (options === void 0) { options = {}; }
            return collection.findOne(query, options);
        },
        find: function (query, options) {
            if (query === void 0) { query = {}; }
            if (options === void 0) { options = {}; }
            var findOptions = __assign({}, (options || {}));
            var sort = findOptions.sort;
            var skip = findOptions.skip;
            var limit = findOptions.limit;
            delete findOptions.sort;
            delete findOptions.skip;
            delete findOptions.limit;
            var cursor = collection.find(query, findOptions);
            if (sort) {
                cursor = cursor.sort(sort);
            }
            if (typeof skip === 'number') {
                cursor = cursor.skip(skip);
            }
            if (typeof limit === 'number') {
                cursor = cursor.limit(limit);
            }
            return cursor.toArray();
        },
        insertOne: function (document, options) {
            if (options === void 0) { options = {}; }
            return collection.insertOne(document, options);
        },
        updateOne: function (query, update, options) {
            if (options === void 0) { options = {}; }
            return collection.updateOne(query, update, options);
        },
        findOneAndUpdate: function (query_1, update_1) {
            var args_1 = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args_1[_i - 2] = arguments[_i];
            }
            return __awaiter(_this, __spreadArray([query_1, update_1], __read(args_1), false), void 0, function (query, update, options) {
                var result;
                if (options === void 0) { options = {}; }
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, collection.findOneAndUpdate(query, update, options)];
                        case 1:
                            result = _a.sent();
                            if (result && typeof result === 'object' && Object.prototype.hasOwnProperty.call(result, 'value')) {
                                return [2 /*return*/, result.value];
                            }
                            return [2 /*return*/, result];
                    }
                });
            });
        },
        findById: function (id, options) {
            if (options === void 0) { options = {}; }
            return collection.findOne({ _id: id }, options);
        },
        createIndex: function (spec, options) {
            if (options === void 0) { options = {}; }
            return collection.createIndex(spec, options);
        }
    };
}
function ensureCollectionIndexes(collections) {
    var _this = this;
    if (indexesEnsured) {
        return;
    }
    indexesEnsured = true;
    setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
        var error_1, error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 6, , 7]);
                    if (!(typeof collections.ErrorAutoFixLogs.createIndex === 'function')) return [3 /*break*/, 5];
                    return [4 /*yield*/, collections.ErrorAutoFixLogs.createIndex({ email_hash: 1 })];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, collections.ErrorAutoFixLogs.createIndex({ issue_hash: 1 })];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, collections.ErrorAutoFixLogs.createIndex({ status: 1 })];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, collections.ErrorAutoFixLogs.createIndex({ ignored: 1 })];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5: return [3 /*break*/, 7];
                case 6:
                    error_1 = _a.sent();
                    console.error('Failed to ensure error auto-fix indexes', error_1);
                    return [3 /*break*/, 7];
                case 7:
                    _a.trys.push([7, 18, , 19]);
                    if (!(typeof collections.SlowQueryLogs.createIndex === 'function')) return [3 /*break*/, 17];
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ query_hash: 1 })];
                case 8:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ collection: 1 })];
                case 9:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ client_slug: 1 })];
                case 10:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ status: 1 })];
                case 11:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ ignored: 1 })];
                case 12:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ last_seen_at: -1 })];
                case 13:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ collection: 1, duration_ms: -1 })];
                case 14:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ publication: 1 })];
                case 15:
                    _a.sent();
                    return [4 /*yield*/, collections.SlowQueryLogs.createIndex({ server_url: 1 })];
                case 16:
                    _a.sent();
                    _a.label = 17;
                case 17: return [3 /*break*/, 19];
                case 18:
                    error_2 = _a.sent();
                    console.error('Failed to ensure slow query indexes', error_2);
                    return [3 /*break*/, 19];
                case 19: return [2 /*return*/];
            }
        });
    }); }, 5000);
}
function registerDiagnosticManagerDependencies(dependencies) {
    if (dependencies === void 0) { dependencies = {}; }
    var errorAutoFixLogs = dependencies.ErrorAutoFixLogs || createCollectionAdapter('error-autofix-logs');
    var slowQueryLogs = dependencies.SlowQueryLogs || createCollectionAdapter('slow-query-logs');
    var aiCoderApps = dependencies.AICoderApps;
    var aiDashboardJobs = dependencies.AIDashboardJobs;
    var errorAutoFixDependencies = {
        ErrorAutoFixLogs: errorAutoFixLogs,
        AICoderApps: aiCoderApps,
        AIDashboardJobs: aiDashboardJobs
    };
    (0, error_auto_fix_manager_1.registerErrorAutoFixManagerDependencies)(errorAutoFixDependencies);
    (0, slow_query_manager_1.registerSlowQueryManagerDependencies)({
        SlowQueryLogs: slowQueryLogs
    });
    var slowQueryVerifierDependencies = {
        SlowQueryLogs: slowQueryLogs,
        AICoderApps: aiCoderApps,
        AIDashboardJobs: aiDashboardJobs
    };
    if (dependencies.checkAICoderTokenEligibility) {
        slowQueryVerifierDependencies.checkAICoderTokenEligibility = dependencies.checkAICoderTokenEligibility;
    }
    (0, slow_query_verifier_manager_1.registerSlowQueryVerifierDependencies)(slowQueryVerifierDependencies);
    ensureCollectionIndexes({
        ErrorAutoFixLogs: errorAutoFixLogs,
        SlowQueryLogs: slowQueryLogs
    });
}

//# sourceMappingURL=diagnostic-manager-bootstrap.js.map
