"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteTask = exports.getAllTasks = exports.findFirstTask = exports.createMicroserviceTasks = void 0;
const MicroserviceTask_model_1 = require("../models/MicroserviceTask.model");
const microservice_task_statuses_enum_1 = require("../enums/microservice-task-statuses.enum");
const createMicroserviceTasks = async (cmd, params, executeAt = new Date(), userId) => {
    const tasks = await MicroserviceTask_model_1.MicroserviceTaskModel.find({ cmd, params, status: microservice_task_statuses_enum_1.EMicroserviceTaskStatuses.SCHEDULED });
    if (!tasks.length) {
        const newTask = await MicroserviceTask_model_1.MicroserviceTaskModel.create({
            userId,
            cmd,
            params,
            status: microservice_task_statuses_enum_1.EMicroserviceTaskStatuses.SCHEDULED,
            executeAt,
        });
        await newTask.save();
    }
};
exports.createMicroserviceTasks = createMicroserviceTasks;
const findFirstTask = async () => {
    const currentDate = new Date();
    const lastTasks = await MicroserviceTask_model_1.MicroserviceTaskModel.aggregate([
        {
            $match: {
                'status': microservice_task_statuses_enum_1.EMicroserviceTaskStatuses.SCHEDULED,
                $or: [
                    { 'executeAt': { $exists: false } },
                    { 'executeAt': { $lte: currentDate } },
                ],
            },
        }, {
            $sort: {
                'createdAt': 1,
            },
        }, {
            $limit: 1,
        },
    ]);
    if (lastTasks.length) {
        return lastTasks[0];
    }
    return null;
};
exports.findFirstTask = findFirstTask;
const getAllTasks = async () => {
    return MicroserviceTask_model_1.MicroserviceTaskModel
        .find({})
        .sort({ 'createdAt': 1 });
};
exports.getAllTasks = getAllTasks;
const deleteTask = async (taskId) => {
    await MicroserviceTask_model_1.MicroserviceTaskModel
        .findByIdAndDelete(taskId);
};
exports.deleteTask = deleteTask;
