import { contextConfigs } from "../../db/manage/manage-schema.js";
import { generateId } from "../../utils/conversations.js";
import { agentScopedWhere } from "./scope-helpers.js";
import { and, count, desc, eq, sql } from "drizzle-orm";

//#region src/data-access/manage/contextConfigs.ts
const getContextConfigById = (db) => async (params) => {
	return await db.query.contextConfigs.findFirst({ where: and(agentScopedWhere(contextConfigs, params.scopes), eq(contextConfigs.id, params.id)) });
};
const listContextConfigs = (db) => async (params) => {
	return await db.query.contextConfigs.findMany({
		where: agentScopedWhere(contextConfigs, params.scopes),
		orderBy: [desc(contextConfigs.createdAt)]
	});
};
const listContextConfigsPaginated = (db) => async (params) => {
	const page = params.pagination?.page || 1;
	const limit = Math.min(params.pagination?.limit || 10, 100);
	const offset = (page - 1) * limit;
	const whereClause = agentScopedWhere(contextConfigs, params.scopes);
	const [contextConfigList, totalResult] = await Promise.all([db.select().from(contextConfigs).where(whereClause).limit(limit).offset(offset).orderBy(desc(contextConfigs.createdAt)), db.select({ count: sql`COUNT(*)` }).from(contextConfigs).where(whereClause)]);
	const total = Number(totalResult[0]?.count || 0);
	return {
		data: contextConfigList,
		pagination: {
			page,
			limit,
			total,
			pages: Math.ceil(total / limit)
		}
	};
};
const createContextConfig = (db) => async (params) => {
	const id = params.id || generateId();
	const now = (/* @__PURE__ */ new Date()).toISOString();
	let contextVariables = params.contextVariables;
	if (contextVariables !== void 0 && contextVariables !== null && typeof contextVariables === "object" && Object.keys(contextVariables).length === 0) contextVariables = null;
	return (await db.insert(contextConfigs).values({
		id,
		tenantId: params.tenantId,
		projectId: params.projectId,
		agentId: params.agentId,
		headersSchema: params.headersSchema ?? null,
		contextVariables: contextVariables ?? null,
		createdAt: now,
		updatedAt: now
	}).returning())[0];
};
const updateContextConfig = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const processedData = { ...params.data };
	if ("contextVariables" in params.data) {
		if (params.data.contextVariables === null || typeof params.data.contextVariables === "object" && params.data.contextVariables !== null && Object.keys(params.data.contextVariables).length === 0) processedData.contextVariables = null;
	}
	if ("headersSchema" in params.data && params.data.headersSchema === null) processedData.headersSchema = null;
	return (await db.update(contextConfigs).set({
		...processedData,
		updatedAt: now
	}).where(and(agentScopedWhere(contextConfigs, params.scopes), eq(contextConfigs.id, params.id))).returning())[0];
};
const deleteContextConfig = (db) => async (params) => {
	try {
		return (await db.delete(contextConfigs).where(and(agentScopedWhere(contextConfigs, params.scopes), eq(contextConfigs.id, params.id))).returning()).length > 0;
	} catch (error) {
		console.error("Error deleting context config:", error);
		return false;
	}
};
const hasContextConfig = (db) => async (params) => {
	return await getContextConfigById(db)(params) !== null;
};
const countContextConfigs = (db) => async (params) => {
	const total = (await db.select({ count: count() }).from(contextConfigs).where(agentScopedWhere(contextConfigs, params.scopes)))[0]?.count || 0;
	return typeof total === "string" ? Number.parseInt(total, 10) : total;
};
/**
* Upsert a context config (create if it doesn't exist, update if it does)
*/
const upsertContextConfig = (db) => async (params) => {
	const scopes = {
		tenantId: params.data.tenantId,
		projectId: params.data.projectId,
		agentId: params.data.agentId
	};
	if (params.data.id) {
		if (await getContextConfigById(db)({
			scopes,
			id: params.data.id
		})) return await updateContextConfig(db)({
			scopes,
			id: params.data.id,
			data: {
				headersSchema: params.data.headersSchema,
				contextVariables: params.data.contextVariables
			}
		});
	}
	return await createContextConfig(db)(params.data);
};

//#endregion
export { countContextConfigs, createContextConfig, deleteContextConfig, getContextConfigById, hasContextConfig, listContextConfigs, listContextConfigsPaginated, updateContextConfig, upsertContextConfig };