/**
 * When a feature setting gets updated we will handle it here.
 * we will stop jobs, stop cycles
 */

import { dbCleanup } from "../db/dbCleanup.controller.js";
import type { Setting } from "../db/schema/settings.schema.js";
import { monitorReleaseChanges } from "../opendock/openDockRreleaseMonitor.utils.js";
import {
	killOpendockSocket,
	opendockSocketMonitor,
} from "../opendock/opendockSocketMonitor.utils.js";
import { monitorAlplaPurchase } from "../purchase/purchase.controller.js";
import {
	createCronJob,
	resumeCronJob,
	stopCronJob,
} from "../utils/croner.utils.js";

export const featureControl = async (data: Setting) => {
	// when a feature is changed to active or deactivated we will update the cron.
	if (data.active) {
		resumeCronJob(data.name);
	} else {
		stopCronJob(data.name);
	}

	// specific setting stuff should have handled like below. what needs turned back on or off.
	if (data.name === "opendock_sync" && data.active) {
		opendockSocketMonitor();
		monitorReleaseChanges();
		createCronJob("opendockAptCleanup", "0 30 5 * * *", () =>
			dbCleanup("opendockApt", 90),
		);
	}

	if (data.name === "opendock_sync" && !data.active) {
		killOpendockSocket();
		stopCronJob("opendockAptCleanup");
	}

	// purchase stuff
	if (data.name === "purchaseMonitor" && data.active) {
		monitorAlplaPurchase();
	}

	if (data.name === "purchaseMonitor" && !data.active) {
		stopCronJob("purchaseMonitor");
	}

	// this means the data time has changed
	if (data.name === "purchaseMonitor" && data.value) {
		monitorAlplaPurchase();
	}
};
