"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 { InternalTables } = require("../db/utils");
const { getGlobalUser } = require("../utilities/global");
const { getAppDB } = require("@devlego/backend-core/context");
const { getProdAppID } = require("@devlego/backend-core/db");
exports.getFullUser = (ctx, userId) => __awaiter(void 0, void 0, void 0, function* () {
    const global = yield getGlobalUser(userId);
    let metadata;
    try {
        // this will throw an error if the db doesn't exist, or there is no appId
        const db = getAppDB();
        metadata = yield db.get(userId);
    }
    catch (err) {
        // it is fine if there is no user metadata, just remove global db info
        delete global._id;
        delete global._rev;
    }
    return Object.assign(Object.assign(Object.assign({}, global), metadata), { tableId: InternalTables.USER_METADATA, 
        // make sure the ID is always a local ID, not a global one
        _id: userId });
});
exports.publicApiUserFix = ctx => {
    if (!ctx.request.body) {
        return ctx;
    }
    if (!ctx.request.body._id && ctx.params.userId) {
        ctx.request.body._id = ctx.params.userId;
    }
    if (!ctx.request.body.roles) {
        ctx.request.body.roles = {};
    }
    else {
        const newRoles = {};
        for (let [appId, role] of Object.entries(ctx.request.body.roles)) {
            // @ts-ignore
            newRoles[getProdAppID(appId)] = role;
        }
        ctx.request.body.roles = newRoles;
    }
    return ctx;
};
