import { schedulerState } from "../../db/runtime/runtime-schema.js";
import { eq, sql } from "drizzle-orm";

//#region src/data-access/runtime/schedulerState.ts
const SINGLETON_ID = "singleton";
const getSchedulerState = (db) => async () => {
	return await db.query.schedulerState.findFirst({ where: eq(schedulerState.id, SINGLETON_ID) });
};
const upsertSchedulerState = (db) => async (params) => {
	const [row] = await db.insert(schedulerState).values({
		id: SINGLETON_ID,
		currentRunId: params.currentRunId
	}).onConflictDoUpdate({
		target: schedulerState.id,
		set: {
			currentRunId: params.currentRunId,
			updatedAt: sql`now()`.mapWith(String)
		}
	}).returning();
	return row;
};
const clearSchedulerState = (db) => async () => {
	await db.update(schedulerState).set({
		currentRunId: null,
		updatedAt: sql`now()`.mapWith(String)
	}).where(eq(schedulerState.id, SINGLETON_ID));
};

//#endregion
export { clearSchedulerState, getSchedulerState, upsertSchedulerState };