import { functions } from "../../db/manage/manage-schema.js";
import { projectScopedWhere } from "./scope-helpers.js";
import { and, count, desc, eq } from "drizzle-orm";

//#region src/data-access/manage/functions.ts
/**
* Create or update a function (project-scoped)
*/
const upsertFunction = (db) => async (params) => {
	const { data, scopes } = params;
	const { tenantId, projectId } = scopes;
	let dependencies = data.dependencies;
	if (!dependencies || Object.keys(dependencies).length === 0) {
		const { autoDetectDependencies } = await import("../../utils/detectDependencies.js");
		dependencies = autoDetectDependencies(data.executeCode);
	}
	if ((await db.select().from(functions).where(and(projectScopedWhere(functions, scopes), eq(functions.id, data.id))).limit(1)).length > 0) await db.update(functions).set({
		inputSchema: data.inputSchema,
		executeCode: data.executeCode,
		dependencies,
		updatedAt: (/* @__PURE__ */ new Date()).toISOString()
	}).where(and(projectScopedWhere(functions, scopes), eq(functions.id, data.id)));
	else await db.insert(functions).values({
		tenantId,
		projectId,
		id: data.id,
		inputSchema: data.inputSchema,
		executeCode: data.executeCode,
		dependencies,
		createdAt: (/* @__PURE__ */ new Date()).toISOString(),
		updatedAt: (/* @__PURE__ */ new Date()).toISOString()
	});
};
/**
* Get a function by ID (project-scoped)
*/
const getFunction = (db) => async (params) => {
	const { functionId, scopes } = params;
	return (await db.select().from(functions).where(and(projectScopedWhere(functions, scopes), eq(functions.id, functionId))).limit(1))[0] || null;
};
/**
* List all functions for a project
*/
const listFunctions = (db) => async (params) => {
	const { scopes } = params;
	return await db.select().from(functions).where(projectScopedWhere(functions, scopes));
};
/**
* List all functions for a project with pagination
*/
const listFunctionsPaginated = (db) => async (params) => {
	const { scopes, pagination } = params;
	const page = pagination?.page || 1;
	const limit = Math.min(pagination?.limit || 10, 100);
	const offset = (page - 1) * limit;
	const whereClause = projectScopedWhere(functions, scopes);
	const [data, totalResult] = await Promise.all([db.select().from(functions).where(whereClause).limit(limit).offset(offset).orderBy(desc(functions.createdAt)), db.select({ count: count() }).from(functions).where(whereClause)]);
	const total = totalResult[0]?.count || 0;
	return {
		data,
		pagination: {
			page,
			limit,
			total,
			pages: Math.ceil(total / limit)
		}
	};
};
/**
* Delete a function (project-scoped)
*/
const deleteFunction = (db) => async (params) => {
	const { functionId, scopes } = params;
	await db.delete(functions).where(and(projectScopedWhere(functions, scopes), eq(functions.id, functionId)));
};

//#endregion
export { deleteFunction, getFunction, listFunctions, listFunctionsPaginated, upsertFunction };