"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.backfill = void 0;
const backend_core_1 = require("@devlego/backend-core");
const types_1 = require("@devlego/types");
const environment_1 = __importDefault(require("./../../../../environment"));
const getConfigs = (globalDb) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield globalDb.allDocs(backend_core_1.db.getConfigParams({}, {
        include_docs: true,
    }));
    return response.rows.map((row) => row.doc);
});
const backfill = (globalDb, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
    const configs = yield getConfigs(globalDb);
    for (const config of configs) {
        if ((0, types_1.isSMTPConfig)(config)) {
            yield backend_core_1.events.email.SMTPCreated(timestamp);
        }
        if ((0, types_1.isGoogleConfig)(config)) {
            yield backend_core_1.events.auth.SSOCreated("google", timestamp);
            if (config.config.activated) {
                yield backend_core_1.events.auth.SSOActivated("google", timestamp);
            }
        }
        if ((0, types_1.isOIDCConfig)(config)) {
            yield backend_core_1.events.auth.SSOCreated("oidc", timestamp);
            if (config.config.configs[0].activated) {
                yield backend_core_1.events.auth.SSOActivated("oidc", timestamp);
            }
        }
        if ((0, types_1.isSettingsConfig)(config)) {
            const company = config.config.company;
            if (company && company !== "Budibase") {
                yield backend_core_1.events.org.nameUpdated(timestamp);
            }
            const logoUrl = config.config.logoUrl;
            if (logoUrl) {
                yield backend_core_1.events.org.logoUpdated(timestamp);
            }
            const platformUrl = config.config.platformUrl;
            if (platformUrl &&
                platformUrl !== "http://localhost:10000" &&
                environment_1.default.SELF_HOSTED) {
                yield backend_core_1.events.org.platformURLUpdated(timestamp);
            }
        }
    }
});
exports.backfill = backfill;
