"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.backfill = exports.getUsers = void 0;
const backend_core_1 = require("@devlego/backend-core");
const __1 = require("..");
// manually define user doc params - normally server doesn't read users from the db
const getUserParams = (props) => {
    return backend_core_1.db.getDocParams(backend_core_1.db.DocumentTypes.USER, null, props);
};
const getUsers = (globalDb) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield globalDb.allDocs(getUserParams({
        include_docs: true,
    }));
    return response.rows.map((row) => row.doc);
});
exports.getUsers = getUsers;
const backfill = (globalDb, account) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const users = yield (0, exports.getUsers)(globalDb);
    for (const user of users) {
        let timestamp = __1.DEFAULT_TIMESTAMP;
        if (user.createdAt) {
            timestamp = user.createdAt;
        }
        yield backend_core_1.events.identification.identifyUser(user, account, timestamp);
        yield backend_core_1.events.user.created(user, timestamp);
        if ((_a = user.admin) === null || _a === void 0 ? void 0 : _a.global) {
            yield backend_core_1.events.user.permissionAdminAssigned(user, timestamp);
        }
        if ((_b = user.builder) === null || _b === void 0 ? void 0 : _b.global) {
            yield backend_core_1.events.user.permissionBuilderAssigned(user, timestamp);
        }
        if (user.roles) {
            for (const [appId, role] of Object.entries(user.roles)) {
                yield backend_core_1.events.role.assigned(user, role, timestamp);
            }
        }
    }
    return users.length;
});
exports.backfill = backfill;
