"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.deployApp = exports.deploymentProgress = exports.fetchDeployments = void 0;
const Deployment_1 = __importDefault(require("./Deployment"));
const db_1 = require("@devlego/backend-core/db");
const utils_1 = require("../../../db/utils");
const utils_2 = require("../../../automations/utils");
const cache_1 = require("@devlego/backend-core/cache");
const context_1 = require("@devlego/backend-core/context");
const pro_1 = require("@devlego/pro");
const backend_core_1 = require("@devlego/backend-core");
// the max time we can wait for an invalidation to complete before considering it failed
const MAX_PENDING_TIME_MS = 30 * 60000;
const DeploymentStatus = {
    SUCCESS: "SUCCESS",
    PENDING: "PENDING",
    FAILURE: "FAILURE",
};
// checks that deployments are in a good state, any pending will be updated
function checkAllDeployments(deployments) {
    return __awaiter(this, void 0, void 0, function* () {
        let updated = false;
        let deployment;
        for (deployment of Object.values(deployments.history)) {
            // check that no deployments have crashed etc and are now stuck
            if (deployment.status === DeploymentStatus.PENDING &&
                Date.now() - deployment.updatedAt > MAX_PENDING_TIME_MS) {
                deployment.status = DeploymentStatus.FAILURE;
                deployment.err = "Timed out";
                updated = true;
            }
        }
        return { updated, deployments };
    });
}
function storeDeploymentHistory(deployment) {
    return __awaiter(this, void 0, void 0, function* () {
        const deploymentJSON = deployment.getJSON();
        const db = (0, context_1.getAppDB)();
        let deploymentDoc;
        try {
            // theres only one deployment doc per app database
            deploymentDoc = yield db.get(utils_1.DocumentTypes.DEPLOYMENTS);
        }
        catch (err) {
            deploymentDoc = { _id: utils_1.DocumentTypes.DEPLOYMENTS, history: {} };
        }
        const deploymentId = deploymentJSON._id;
        // first time deployment
        if (!deploymentDoc.history[deploymentId])
            deploymentDoc.history[deploymentId] = {};
        deploymentDoc.history[deploymentId] = Object.assign(Object.assign(Object.assign({}, deploymentDoc.history[deploymentId]), deploymentJSON), { updatedAt: Date.now() });
        yield db.put(deploymentDoc);
        deployment.fromJSON(deploymentDoc.history[deploymentId]);
        return deployment;
    });
}
function initDeployedApp(prodAppId) {
    return __awaiter(this, void 0, void 0, function* () {
        const db = (0, context_1.getProdAppDB)();
        console.log("Reading automation docs");
        const automations = (yield db.allDocs((0, utils_1.getAutomationParams)(null, {
            include_docs: true,
        }))).rows.map((row) => row.doc);
        console.log("You have " + automations.length + " automations");
        const promises = [];
        console.log("Disabling prod crons..");
        yield (0, utils_2.disableAllCrons)(prodAppId);
        console.log("Prod Cron triggers disabled..");
        console.log("Enabling cron triggers for deployed app..");
        for (let automation of automations) {
            promises.push((0, utils_2.enableCronTrigger)(prodAppId, automation));
        }
        yield Promise.all(promises);
        console.log("Enabled cron triggers for deployed app..");
    });
}
function deployApp(deployment) {
    return __awaiter(this, void 0, void 0, function* () {
        let replication;
        try {
            const appId = (0, context_1.getAppId)();
            const devAppId = (0, db_1.getDevelopmentAppID)(appId);
            const productionAppId = (0, db_1.getProdAppID)(appId);
            const config = {
                source: devAppId,
                target: productionAppId,
            };
            replication = new db_1.Replication(config);
            console.log("Replication object created");
            yield replication.replicate();
            console.log("replication complete.. replacing app meta doc");
            const db = (0, context_1.getProdAppDB)();
            const appDoc = yield db.get(utils_1.DocumentTypes.APP_METADATA);
            deployment.appUrl = appDoc.url;
            appDoc.appId = productionAppId;
            appDoc.instance._id = productionAppId;
            yield db.put(appDoc);
            yield cache_1.app.invalidateAppMetadata(productionAppId);
            console.log("New app doc written successfully.");
            yield initDeployedApp(productionAppId);
            console.log("Deployed app initialised, setting deployment to successful");
            deployment.setStatus(DeploymentStatus.SUCCESS);
            yield storeDeploymentHistory(deployment);
            return appDoc;
        }
        catch (err) {
            deployment.setStatus(DeploymentStatus.FAILURE, err.message);
            yield storeDeploymentHistory(deployment);
            throw Object.assign(Object.assign({}, err), { message: `Deployment Failed: ${err.message}` });
        }
        finally {
            if (replication) {
                yield replication.close();
            }
        }
    });
}
function fetchDeployments(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const db = (0, context_1.getAppDB)();
            const deploymentDoc = yield db.get(utils_1.DocumentTypes.DEPLOYMENTS);
            const { updated, deployments } = yield checkAllDeployments(deploymentDoc);
            if (updated) {
                yield db.put(deployments);
            }
            ctx.body = Object.values(deployments.history).reverse();
        }
        catch (err) {
            ctx.body = [];
        }
    });
}
exports.fetchDeployments = fetchDeployments;
function deploymentProgress(ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const db = (0, context_1.getAppDB)();
            const deploymentDoc = yield db.get(utils_1.DocumentTypes.DEPLOYMENTS);
            ctx.body = deploymentDoc[ctx.params.deploymentId];
        }
        catch (err) {
            ctx.throw(500, `Error fetching data for deployment ${ctx.params.deploymentId}`);
        }
    });
}
exports.deploymentProgress = deploymentProgress;
const isFirstDeploy = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const db = (0, context_1.getProdAppDB)();
        yield db.get(utils_1.DocumentTypes.APP_METADATA);
    }
    catch (e) {
        if (e.status === 404) {
            return true;
        }
        throw e;
    }
    return false;
});
const _deployApp = function (ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        let deployment = new Deployment_1.default();
        console.log("Deployment object created");
        deployment.setStatus(DeploymentStatus.PENDING);
        console.log("Deployment object set to pending");
        deployment = yield storeDeploymentHistory(deployment);
        console.log("Stored deployment history");
        console.log("Deploying app...");
        let app;
        if (yield isFirstDeploy()) {
            app = yield pro_1.quotas.addPublishedApp(() => deployApp(deployment));
        }
        else {
            app = yield deployApp(deployment);
        }
        yield backend_core_1.events.app.published(app);
        ctx.body = deployment;
    });
};
exports.deployApp = _deployApp;
