"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 { outputProcessing } = require("../../utilities/rowProcessor");
const { InternalTables } = require("../../db/utils");
const { getFullUser } = require("../../utilities/users");
const { BUILTIN_ROLE_IDS } = require("@devlego/backend-core/roles");
const { getAppDB, getAppId } = require("@devlego/backend-core/context");
exports.fetchSelf = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    let userId = ctx.user.userId || ctx.user._id;
    /* istanbul ignore next */
    if (!userId || !ctx.isAuthenticated) {
        ctx.body = {};
        return;
    }
    const user = yield getFullUser(ctx, userId);
    // this shouldn't be returned by the app self
    delete user.roles;
    // forward the csrf token from the session
    user.csrfToken = ctx.user.csrfToken;
    if (getAppId()) {
        const db = getAppDB();
        // remove the full roles structure
        delete user.roles;
        try {
            const userTable = yield db.get(InternalTables.USER_METADATA);
            const metadata = yield db.get(userId);
            // make sure there is never a stale csrf token
            delete metadata.csrfToken;
            // specifically needs to make sure is enriched
            ctx.body = yield outputProcessing(userTable, Object.assign(Object.assign({}, user), metadata));
        }
        catch (err) {
            let response;
            // user didn't exist in app, don't pretend they do
            if (user.roleId === BUILTIN_ROLE_IDS.PUBLIC) {
                response = {};
            }
            // user has a role of some sort, return them
            else if (err.status === 404) {
                const metadata = Object.assign(Object.assign({}, user), { _id: userId });
                const dbResp = yield db.put(metadata);
                user._rev = dbResp.rev;
                response = user;
            }
            else {
                response = user;
            }
            ctx.body = response;
        }
    }
    else {
        ctx.body = user;
    }
});
