"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInstallTimestamp = exports.isComplete = exports.run = void 0;
const users = __importStar(require("./global/users"));
const configs = __importStar(require("./global/configs"));
const quotas = __importStar(require("./global/quotas"));
const backend_core_1 = require("@devlego/backend-core");
const types_1 = require("@devlego/types");
const environment_1 = __importDefault(require("../../../environment"));
const _1 = require(".");
const failGraceful = environment_1.default.SELF_HOSTED && !environment_1.default.isDev();
const handleError = (e, errors) => {
    if (failGraceful) {
        if (errors) {
            errors.push(e);
        }
        return;
    }
    throw e;
};
const formatUsage = (usage) => {
    let maxAutomations = 0;
    let maxQueries = 0;
    let rows = 0;
    let developers = 0;
    if (usage) {
        if (usage.usageQuota) {
            rows = usage.usageQuota.rows;
            developers = usage.usageQuota.developers;
        }
        if (usage.monthly) {
            for (const value of Object.values(usage.monthly)) {
                if (value.automations > maxAutomations) {
                    maxAutomations = value.automations;
                }
                if (value.queries > maxQueries) {
                    maxQueries = value.queries;
                }
            }
        }
    }
    return {
        maxAutomations,
        maxQueries,
        rows,
        developers,
    };
};
const EVENTS = [
    types_1.Event.EMAIL_SMTP_CREATED,
    types_1.Event.AUTH_SSO_CREATED,
    types_1.Event.AUTH_SSO_ACTIVATED,
    types_1.Event.ORG_NAME_UPDATED,
    types_1.Event.ORG_LOGO_UPDATED,
    types_1.Event.ORG_PLATFORM_URL_UPDATED,
    types_1.Event.USER_CREATED,
    types_1.Event.USER_PERMISSION_ADMIN_ASSIGNED,
    types_1.Event.USER_PERMISSION_BUILDER_ASSIGNED,
    types_1.Event.ROLE_ASSIGNED,
    types_1.Event.ROWS_CREATED,
    types_1.Event.QUERIES_RUN,
    types_1.Event.AUTOMATIONS_RUN,
];
/**
 * Date:
 * May 2022
 *
 * Description:
 * Backfill global events.
 */
const run = (db) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const tenantId = backend_core_1.tenancy.getTenantId();
        let timestamp = _1.DEFAULT_TIMESTAMP;
        const totals = {};
        const errors = [];
        let allUsers = [];
        try {
            allUsers = yield users.getUsers(db);
        }
        catch (e) {
            handleError(e, errors);
        }
        if (!allUsers || allUsers.length === 0) {
            // first time startup - we don't need to backfill anything
            // tenant will be identified when admin user is created
            if (environment_1.default.SELF_HOSTED) {
                yield backend_core_1.events.installation.firstStartup();
            }
            return;
        }
        try {
            const installTimestamp = yield (0, exports.getInstallTimestamp)(db, allUsers);
            if (installTimestamp) {
                timestamp = installTimestamp;
            }
        }
        catch (e) {
            handleError(e, errors);
        }
        let account;
        if (!environment_1.default.SELF_HOSTED && !environment_1.default.DISABLE_ACCOUNT_PORTAL) {
            account = yield backend_core_1.accounts.getAccountByTenantId(tenantId);
        }
        try {
            yield backend_core_1.events.identification.identifyTenantGroup(tenantId, account, timestamp);
        }
        catch (e) {
            handleError(e, errors);
        }
        // tell the event pipeline to start caching
        // events for this tenant
        yield backend_core_1.events.backfillCache.start(EVENTS);
        try {
            yield configs.backfill(db, timestamp);
        }
        catch (e) {
            handleError(e, errors);
        }
        try {
            totals.users = yield users.backfill(db, account);
        }
        catch (e) {
            handleError(e, errors);
        }
        try {
            const allApps = yield backend_core_1.db.getAllApps({ dev: true });
            totals.apps = allApps.length;
            totals.usage = yield quotas.backfill(allApps);
        }
        catch (e) {
            handleError(e, errors);
        }
        const properties = Object.assign(Object.assign({ apps: totals.apps, users: totals.users }, formatUsage(totals.usage)), { usage: totals.usage });
        if (errors.length) {
            properties.errors = errors.map((e) => JSON.stringify(e, Object.getOwnPropertyNames(e)));
            properties.errorCount = errors.length;
        }
        else {
            properties.errorCount = 0;
        }
        yield backend_core_1.events.backfill.tenantSucceeded(properties);
        // tell the event pipeline to stop caching events for this tenant
        yield backend_core_1.events.backfillCache.end();
    }
    catch (e) {
        handleError(e);
        yield backend_core_1.events.backfill.tenantFailed(e);
    }
});
exports.run = run;
const isComplete = () => __awaiter(void 0, void 0, void 0, function* () {
    const globalDb = backend_core_1.tenancy.getGlobalDB();
    const migrationsDoc = yield backend_core_1.migrations.getMigrationsDoc(globalDb);
    return !!migrationsDoc.event_global_backfill;
});
exports.isComplete = isComplete;
const getInstallTimestamp = (globalDb, allUsers) => __awaiter(void 0, void 0, void 0, function* () {
    if (!allUsers) {
        allUsers = yield users.getUsers(globalDb);
    }
    // get the oldest user timestamp
    if (allUsers) {
        const timestamps = allUsers
            .map(user => user.createdAt)
            .filter(timestamp => !!timestamp)
            .sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
        if (timestamps.length) {
            return timestamps[0];
        }
    }
});
exports.getInstallTimestamp = getInstallTimestamp;
