import { model, Schema } from 'mongoose';
import { asc, byString } from 'sort-lib';
import cronstrue from 'cronstrue';
const cronStatusSchema = new Schema({
    date: { type: Date, required: true },
    status: { type: String, required: true },
    name: { type: String, required: true },
}, { capped: { max: 5000, size: 100000 } });
cronStatusSchema.index({
    date: -1,
    name: 1,
});
const CronStatusModel = model('CronStatus', cronStatusSchema);
export const appendCronLog = (name, status) => {
    return CronStatusModel.create({
        name,
        date: new Date(),
        status,
    });
};
const cronDefs = new Map();
export const registerCron = (name, timePattern) => {
    cronDefs.set(name, timePattern);
};
export const getCronStatusOverview = async () => {
    const cronStatuses = await CronStatusModel.aggregate([
        { $sort: { date: -1 } },
        {
            $group: {
                _id: '$name',
                date: { $first: '$date' },
                status: { $first: '$status' },
            },
        },
    ]);
    const byKey = new Map();
    cronStatuses.forEach(c => {
        byKey.set(c._id, { date: c.date, status: c.status });
    });
    return [...cronDefs.entries()].sort(asc(byString(x => x[0]))).map(([name, pattern]) => {
        var _a, _b;
        return {
            name,
            frequency: cronstrue.toString(pattern),
            date: (_a = byKey.get(name)) === null || _a === void 0 ? void 0 : _a.date,
            status: (_b = byKey.get(name)) === null || _b === void 0 ? void 0 : _b.status,
        };
    });
};
