import { Router } from "express";
import { getAllJobs, resumeCronJob, stopCronJob } from "./croner.utils.js";
import { apiReturn } from "./returnHelper.utils.js";

const r = Router();

r.patch("/:status", async (req, res) => {
	const { status } = req.params;
	const body = req.body;

	if (!body.name) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "utils",
			subModule: "jobs",
			message: "Missing manadatory name ",
			data: getAllJobs(),
			status: 400,
		});
	}

	const statusCheck = ["start", "stop"];
	if (!statusCheck.includes(status)) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "utils",
			subModule: "jobs",
			message: "You have passed an invalid option please try again. ",
			data: getAllJobs(),
			status: 400,
		});
	}

	if (status === "start") {
		resumeCronJob(body.name);
		return apiReturn(res, {
			success: true,
			level: "info",
			module: "utils",
			subModule: "jobs",
			message: `${body.name} was restarted`,
			data: getAllJobs(),
			status: 200,
		});
	}

	if (status === "stop") {
		stopCronJob(body.name);
		return apiReturn(res, {
			success: true,
			level: "info",
			module: "utils",
			subModule: "jobs",
			message: `${body.name} was stopped`,
			data: getAllJobs(),
			status: 200,
		});
	}
});

export default r;
