"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateCron = exports.formatRouteScheduleMapAsTable = void 0;
const fs_1 = require("fs");
const client_1 = require("../../client");
const detect_cron_1 = require("./detect-cron");
const config = __importStar(require("../../client/config"));
const easy_table_1 = __importDefault(require("easy-table"));
async function clearOldInstance() {
    const client = new client_1.QuirrelClient({
        async handler() { },
        route: "",
        config: {
            quirrelBaseUrl: config.getOldQuirrelBaseUrl(),
            token: config.getOldQuirrelToken(),
        },
    });
    const endpointsResponse = await client.makeRequest("/queues/update-cron", {
        method: "PUT",
        body: JSON.stringify({
            baseUrl: config.withoutTrailingSlash(config.prefixWithProtocol(config.getApplicationBaseUrl())),
            crons: [],
        }),
        headers: { "content-type": "application/json" },
    });
    if (endpointsResponse.status !== 200) {
        throw new Error("Failed to clear old instance: " + (await endpointsResponse.text()));
    }
    console.log("Cleared old instance.");
}
function formatRouteScheduleMapAsTable(jobs) {
    return easy_table_1.default.print(jobs.map((job) => ({
        Route: job.route,
        Schedule: job.schedule,
    })));
}
exports.formatRouteScheduleMapAsTable = formatRouteScheduleMapAsTable;
async function updateCron(scheduleMap, dryRun, production) {
    if (production) {
        process.env.NODE_ENV = "production";
    }
    const quirrel = new client_1.QuirrelClient({
        async handler() { },
        route: "",
    });
    console.log("Jobs:\n");
    console.log(formatRouteScheduleMapAsTable(scheduleMap));
    console.log("Updating server ... ");
    const endpointsResponse = await quirrel.makeRequest("/queues/update-cron", {
        method: "PUT",
        body: JSON.stringify({
            baseUrl: config.withoutTrailingSlash(config.prefixWithProtocol(config.getApplicationBaseUrl())),
            crons: scheduleMap,
            dryRun,
        }),
        headers: { "content-type": "application/json" },
    });
    if (endpointsResponse.status !== 200) {
        console.error("Something went wrong: " + (await endpointsResponse.text()));
        return;
    }
    if (dryRun) {
        console.error(`This was a --dry-run, so nothing was applied.`);
    }
    else {
        console.error(`Successfully updated jobs.`);
    }
    const { deleted } = (await endpointsResponse.json());
    if (deleted.length > 0) {
        console.error(`These jobs are obsolete, and ${dryRun ? "would be" : "were"} removed: `);
        deleted.forEach((route) => console.log(route));
    }
    if (!dryRun && config.getOldQuirrelBaseUrl()) {
        await clearOldInstance();
    }
}
exports.updateCron = updateCron;
function registerUpdateCron(program) {
    program
        .command("update-cron [filename]")
        .description("Updates the Quirrel API with cron jobs that have been detected using detect-cron.")
        .option("-d, --dry-run", "Only plan the update, don't execute.", false)
        .option("-p, --production", "Use production config.", false)
        .action(async (filename = "/dev/stdin", { dryRun, production }) => {
        const routeScheduleMapString = await fs_1.promises.readFile(filename, "utf-8");
        const routeScheduleMap = detect_cron_1.RouteScheduleManifestSchema.parse(JSON.parse(routeScheduleMapString));
        await updateCron(routeScheduleMap, dryRun, production);
    });
}
exports.default = registerUpdateCron;
//# sourceMappingURL=update-cron.js.map