"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());
    });
};
const { StaticDatabases } = require("@devlego/backend-core/db");
const { getGlobalDB } = require("@devlego/backend-core/tenancy");
const KEYS_DOC = StaticDatabases.GLOBAL.docs.apiKeys;
function getBuilderMainDoc() {
    return __awaiter(this, void 0, void 0, function* () {
        const db = getGlobalDB();
        try {
            return yield db.get(KEYS_DOC);
        }
        catch (err) {
            // doesn't exist yet, nothing to get
            return {
                _id: KEYS_DOC,
            };
        }
    });
}
function setBuilderMainDoc(doc) {
    return __awaiter(this, void 0, void 0, function* () {
        // make sure to override the ID
        doc._id = KEYS_DOC;
        const db = getGlobalDB();
        return db.put(doc);
    });
}
exports.fetch = function (ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const mainDoc = yield getBuilderMainDoc();
            ctx.body = mainDoc.apiKeys ? mainDoc.apiKeys : {};
        }
        catch (err) {
            /* istanbul ignore next */
            ctx.throw(400, err);
        }
    });
};
exports.update = function (ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const key = ctx.params.key;
        const value = ctx.request.body.value;
        try {
            const mainDoc = yield getBuilderMainDoc();
            if (mainDoc.apiKeys == null) {
                mainDoc.apiKeys = {};
            }
            mainDoc.apiKeys[key] = value;
            const resp = yield setBuilderMainDoc(mainDoc);
            ctx.body = {
                _id: resp.id,
                _rev: resp.rev,
            };
        }
        catch (err) {
            /* istanbul ignore next */
            ctx.throw(400, err);
        }
    });
};
