import { checkSchedulerCurrentStep, dispatchDueTriggersStep, msUntilNextMinuteStep, registerSchedulerStep } from "../steps/schedulerSteps.js";
import { getWorkflowMetadata, sleep } from "workflow";

//#region src/domains/run/workflow/functions/schedulerWorkflow.ts
/**
* Scheduler workflow — single long-lived workflow that ticks every 60 seconds
* and dispatches all due scheduled triggers.
*
* Runs on all environments (Vercel, postgres world, local).
* On Vercel: restarted by a post-deploy CI step to move onto the latest deployment.
* On postgres/local: recovers via orphan recovery on server restart.
*
* Supersession: registers its run ID in `scheduler_state`. On each tick,
* checks if it's still the active scheduler. If a newer scheduler has taken
* over (e.g., deploy restart), this one stops.
*/
async function _schedulerWorkflow() {
	"use workflow";
	const myRunId = getWorkflowMetadata().workflowRunId;
	await registerSchedulerStep({ runId: myRunId });
	while (true) {
		await sleep(await msUntilNextMinuteStep());
		if (!await checkSchedulerCurrentStep({ runId: myRunId })) return {
			status: "superseded",
			runId: myRunId
		};
		await dispatchDueTriggersStep();
	}
}
const schedulerWorkflow = Object.assign(_schedulerWorkflow, { workflowId: "workflow//./src/domains/run/workflow/functions/schedulerWorkflow//_schedulerWorkflow" });

//#endregion
export { schedulerWorkflow };