import { EMicroserviceTask } from '../enums/microservice-task.enum';
import { IMicroserviceTaskDoc, MicroserviceTaskModel } from '../models/MicroserviceTask.model';
import { EMicroserviceTaskStatuses } from '../enums/microservice-task-statuses.enum';

export const createMicroserviceTasks = async (cmd: EMicroserviceTask, params: any, executeAt: Date = new Date(), userId?: string): Promise<void> => {
  const tasks = await MicroserviceTaskModel.find({ cmd, params, status: EMicroserviceTaskStatuses.SCHEDULED });
  if (!tasks.length) {
    const newTask = await MicroserviceTaskModel.create({
      userId,
      cmd,
      params,
      status: EMicroserviceTaskStatuses.SCHEDULED,
      executeAt,
    });
    await newTask.save();
  }
};

export const findFirstTask = async (): Promise<IMicroserviceTaskDoc> => {
  const currentDate = new Date();
  const lastTasks = await MicroserviceTaskModel.aggregate<IMicroserviceTaskDoc>([
    {
      $match: {
        'status': EMicroserviceTaskStatuses.SCHEDULED,
        $or: [
          { 'executeAt': { $exists: false } },
          { 'executeAt': { $lte: currentDate } },
        ],
      },
    }, {
      $sort: {
        'createdAt': 1,
      },
    }, {
      $limit: 1,
    },
  ]);
  if (lastTasks.length) {
    return lastTasks[0];
  }
  return null;
};

export const getAllTasks = async (): Promise<IMicroserviceTaskDoc[]> => {
  return MicroserviceTaskModel
    .find({})
    .sort({ 'createdAt': 1 });
};

export const deleteTask = async (taskId: string): Promise<void> => {
  await MicroserviceTaskModel
    .findByIdAndDelete(taskId);
};
