"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.run = void 0;
const automations = __importStar(require("./app/automations"));
const datasources = __importStar(require("./app/datasources"));
const layouts = __importStar(require("./app/layouts"));
const queries = __importStar(require("./app/queries"));
const roles = __importStar(require("./app/roles"));
const tables = __importStar(require("./app/tables"));
const screens = __importStar(require("./app/screens"));
const global = __importStar(require("./global"));
const types_1 = require("@devlego/types");
const backend_core_1 = require("@devlego/backend-core");
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;
    }
    console.trace(e);
    throw e;
};
const EVENTS = [
    types_1.Event.AUTOMATION_CREATED,
    types_1.Event.AUTOMATION_STEP_CREATED,
    types_1.Event.DATASOURCE_CREATED,
    types_1.Event.LAYOUT_CREATED,
    types_1.Event.QUERY_CREATED,
    types_1.Event.ROLE_CREATED,
    types_1.Event.SCREEN_CREATED,
    types_1.Event.TABLE_CREATED,
    types_1.Event.VIEW_CREATED,
    types_1.Event.VIEW_CALCULATION_CREATED,
    types_1.Event.VIEW_FILTER_CREATED,
    types_1.Event.APP_PUBLISHED,
    types_1.Event.APP_CREATED,
];
/**
 * Date:
 * May 2022
 *
 * Description:
 * Backfill app events.
 */
const run = (appDb) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        if (yield global.isComplete()) {
            // make sure new apps aren't backfilled
            // return if the global migration for this tenant is complete
            // which runs after the app migrations
            return;
        }
        // tell the event pipeline to start caching
        // events for this tenant
        yield backend_core_1.events.backfillCache.start(EVENTS);
        let timestamp = _1.DEFAULT_TIMESTAMP;
        const app = yield appDb.get(backend_core_1.db.DocumentTypes.APP_METADATA);
        if (app.createdAt) {
            timestamp = app.createdAt;
        }
        if (backend_core_1.db.isProdAppID(app.appId)) {
            yield backend_core_1.events.app.published(app, timestamp);
        }
        const totals = {};
        const errors = [];
        if (backend_core_1.db.isDevAppID(app.appId)) {
            yield backend_core_1.events.app.created(app, timestamp);
            try {
                totals.automations = yield automations.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.datasources = yield datasources.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.layouts = yield layouts.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.queries = yield queries.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.roles = yield roles.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.screens = yield screens.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
            try {
                totals.tables = yield tables.backfill(appDb, timestamp);
            }
            catch (e) {
                handleError(e, errors);
            }
        }
        const properties = {
            appId: app.appId,
            automations: totals.automations,
            datasources: totals.datasources,
            layouts: totals.layouts,
            queries: totals.queries,
            roles: totals.roles,
            tables: totals.tables,
            screens: totals.screens,
        };
        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.appSucceeded(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.appFailed(e);
    }
});
exports.run = run;
