"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());
    });
};
const { createBullBoard } = require("@bull-board/api");
const { BullAdapter } = require("@bull-board/api/bullAdapter");
const { KoaAdapter } = require("@bull-board/koa");
const env = require("../environment");
const Queue = env.isTest()
    ? require("../utilities/queue/inMemoryQueue")
    : require("bull");
const { JobQueues } = require("../constants");
const { utils } = require("@devlego/backend-core/redis");
const { opts, redisProtocolUrl } = utils.getRedisOptions();
const CLEANUP_PERIOD_MS = 60 * 1000;
const queueConfig = redisProtocolUrl || { redis: opts };
let cleanupInternal = null;
let automationQueue = new Queue(JobQueues.AUTOMATIONS, queueConfig);
function cleanup() {
    return __awaiter(this, void 0, void 0, function* () {
        yield automationQueue.clean(CLEANUP_PERIOD_MS, "completed");
    });
}
const PATH_PREFIX = "/bulladmin";
exports.init = () => {
    // cleanup the events every 5 minutes
    if (!cleanupInternal) {
        cleanupInternal = setInterval(cleanup, CLEANUP_PERIOD_MS);
        // fire off an initial cleanup
        cleanup().catch(err => {
            console.error(`Unable to cleanup automation queue initially - ${err}`);
        });
    }
    // Set up queues for bull board admin
    const queues = [automationQueue];
    const adapters = [];
    const serverAdapter = new KoaAdapter();
    for (let queue of queues) {
        adapters.push(new BullAdapter(queue));
    }
    createBullBoard({
        queues: adapters,
        serverAdapter,
    });
    serverAdapter.setBasePath(PATH_PREFIX);
    return serverAdapter.registerPlugin();
};
exports.shutdown = () => __awaiter(void 0, void 0, void 0, function* () {
    if (automationQueue) {
        clearInterval(cleanupInternal);
        yield automationQueue.close();
        automationQueue = null;
    }
});
exports.queue = automationQueue;
