import { workflowExecutions } from "../../db/runtime/runtime-schema.js";
import { and, desc, eq } from "drizzle-orm";

//#region src/data-access/runtime/workflowExecutions.ts
const createWorkflowExecution = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [created] = await db.insert(workflowExecutions).values({
		...params,
		createdAt: now,
		updatedAt: now
	}).returning();
	return created;
};
const getWorkflowExecution = (db) => async (params) => {
	return (await db.select().from(workflowExecutions).where(and(eq(workflowExecutions.tenantId, params.tenantId), eq(workflowExecutions.projectId, params.projectId), eq(workflowExecutions.id, params.id))).limit(1))[0] ?? null;
};
const getWorkflowExecutionByConversation = (db) => async (params) => {
	return (await db.select().from(workflowExecutions).where(and(eq(workflowExecutions.tenantId, params.tenantId), eq(workflowExecutions.projectId, params.projectId), eq(workflowExecutions.conversationId, params.conversationId))).orderBy(desc(workflowExecutions.createdAt)).limit(1))[0] ?? null;
};
const updateWorkflowExecutionStatus = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const updateData = {
		status: params.status,
		updatedAt: now
	};
	if (params.metadata !== void 0) updateData.metadata = params.metadata;
	const [updated] = await db.update(workflowExecutions).set(updateData).where(and(eq(workflowExecutions.tenantId, params.tenantId), eq(workflowExecutions.projectId, params.projectId), eq(workflowExecutions.id, params.id))).returning();
	return updated ?? null;
};

//#endregion
export { createWorkflowExecution, getWorkflowExecution, getWorkflowExecutionByConversation, updateWorkflowExecutionStatus };