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

//#region src/data-access/runtime/improvementRuns.ts
const createCoPilotRun = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [created] = await db.insert(coPilotRuns).values({
		...params,
		createdAt: now,
		updatedAt: now
	}).returning();
	return created;
};
const getCoPilotRunByRef = (db) => async (params) => {
	const [match] = await db.select().from(coPilotRuns).where(and(eq(coPilotRuns.tenantId, params.scopes.tenantId), eq(coPilotRuns.projectId, params.scopes.projectId), sql`${coPilotRuns.ref}->>'type' = ${params.ref.type}`, sql`${coPilotRuns.ref}->>'name' = ${params.ref.name}`)).orderBy(desc(coPilotRuns.createdAt)).limit(1);
	return match ?? null;
};
const getCoPilotRunByBranchName = (db) => async (params) => {
	const [match] = await db.select().from(coPilotRuns).where(and(eq(coPilotRuns.tenantId, params.scopes.tenantId), eq(coPilotRuns.projectId, params.scopes.projectId), sql`${coPilotRuns.ref}->>'type' = 'branch'`, sql`${coPilotRuns.ref}->>'name' = ${params.branchName}`)).orderBy(desc(coPilotRuns.createdAt)).limit(1);
	return match ?? null;
};
const listCoPilotRunsByBranchName = (db) => async (params) => {
	return await db.select().from(coPilotRuns).where(and(eq(coPilotRuns.tenantId, params.scopes.tenantId), eq(coPilotRuns.projectId, params.scopes.projectId), sql`${coPilotRuns.ref}->>'type' = 'branch'`, sql`${coPilotRuns.ref}->>'name' = ${params.branchName}`)).orderBy(asc(coPilotRuns.createdAt));
};
const listCoPilotRuns = (db) => async (params) => {
	return await db.select().from(coPilotRuns).where(and(eq(coPilotRuns.tenantId, params.scopes.tenantId), eq(coPilotRuns.projectId, params.scopes.projectId))).orderBy(desc(coPilotRuns.createdAt));
};
const updateCoPilotRunStatusByConversationId = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [updated] = await db.update(coPilotRuns).set({
		status: params.status,
		updatedAt: now
	}).where(eq(coPilotRuns.conversationId, params.conversationId)).returning();
	return updated ?? null;
};
const deleteCoPilotRunsByBranchName = (db) => async (params) => {
	return (await db.delete(coPilotRuns).where(and(eq(coPilotRuns.tenantId, params.scopes.tenantId), eq(coPilotRuns.projectId, params.scopes.projectId), sql`${coPilotRuns.ref}->>'type' = 'branch'`, sql`${coPilotRuns.ref}->>'name' = ${params.branchName}`)).returning()).length;
};

//#endregion
export { createCoPilotRun, deleteCoPilotRunsByBranchName, getCoPilotRunByBranchName, getCoPilotRunByRef, listCoPilotRuns, listCoPilotRunsByBranchName, updateCoPilotRunStatusByConversationId };