"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.search = exports.addRev = void 0;
const { getAppDB } = require("@devlego/backend-core/context");
const utils_1 = require("../../../integrations/utils");
const utils_2 = require("../../../db/utils");
function addRev(body, tableId) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!body._id || (tableId && (0, utils_1.isExternalTable)(tableId))) {
            return body;
        }
        let id = body._id;
        if (body._id.startsWith(utils_2.APP_PREFIX)) {
            id = utils_2.DocumentTypes.APP_METADATA;
        }
        const db = getAppDB();
        const dbDoc = yield db.get(id);
        body._rev = dbDoc._rev;
        // update ID in case it is an app ID
        body._id = id;
        return body;
    });
}
exports.addRev = addRev;
/**
 * Performs a case insensitive search on the provided documents, using the
 * provided key and value. This will be a string based search, using the
 * startsWith function.
 */
function search(docs, value, key = "name") {
    if (!value || typeof value !== "string") {
        return docs;
    }
    value = value.toLowerCase();
    const filtered = [];
    for (let doc of docs) {
        if (typeof doc[key] !== "string") {
            continue;
        }
        const toTest = doc[key].toLowerCase();
        if (toTest.startsWith(value)) {
            filtered.push(doc);
        }
    }
    return filtered;
}
exports.search = search;
