import { contextCache } from "../../db/runtime/runtime-schema.js";
import { generateId } from "../../utils/conversations.js";
import { projectScopedWhere } from "../manage/scope-helpers.js";
import { and, eq } from "drizzle-orm";

//#region src/data-access/runtime/contextCache.ts
/**
* Get cached context data for a conversation with optional request hash validation
*/
const getCacheEntry = (db) => async (params) => {
	try {
		const cacheEntry = await db.query.contextCache.findFirst({ where: and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.conversationId, params.conversationId), eq(contextCache.contextConfigId, params.contextConfigId), eq(contextCache.contextVariableKey, params.contextVariableKey)) });
		if (!cacheEntry) return null;
		if (params.requestHash && cacheEntry.requestHash && cacheEntry.requestHash !== params.requestHash) return null;
		return {
			...cacheEntry,
			value: cacheEntry.value
		};
	} catch {
		return null;
	}
};
/**
* Set cached context data for a conversation
*/
const setCacheEntry = (db) => async (entry) => {
	try {
		const cacheData = {
			id: generateId(),
			tenantId: entry.tenantId,
			projectId: entry.projectId,
			conversationId: entry.conversationId,
			contextConfigId: entry.contextConfigId,
			contextVariableKey: entry.contextVariableKey,
			value: entry.value,
			requestHash: entry.requestHash || null,
			fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
			fetchSource: `${entry.contextConfigId}:${entry.contextVariableKey}`,
			createdAt: (/* @__PURE__ */ new Date()).toISOString(),
			updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
			ref: entry.ref
		};
		const [result] = await db.insert(contextCache).values(cacheData).returning();
		return {
			...result,
			value: result.value
		};
	} catch {
		return null;
	}
};
/**
* Clear cache entries for a specific conversation
*/
const clearConversationCache = (db) => async (params) => {
	return (await db.delete(contextCache).where(and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.conversationId, params.conversationId))).returning()).length;
};
/**
* Clear all cache entries for a specific context configuration
*/
const clearContextConfigCache = (db) => async (params) => {
	return (await db.delete(contextCache).where(and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.contextConfigId, params.contextConfigId))).returning()).length;
};
/**
* Clean up all cache entries for a tenant
*/
const cleanupTenantCache = (db) => async (params) => {
	return (await db.delete(contextCache).where(projectScopedWhere(contextCache, params.scopes)).returning()).length;
};
/**
* Invalidate the headers cache for a conversation
*/
const invalidateHeadersCache = (db) => async (params) => {
	return (await db.delete(contextCache).where(and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.conversationId, params.conversationId), eq(contextCache.contextConfigId, params.contextConfigId), eq(contextCache.contextVariableKey, "headers"))).returning()).length;
};
/**
* Invalidate specific cache entries for invocation-trigger definitions
*/
const invalidateInvocationDefinitionsCache = (db) => async (params) => {
	let totalRowsAffected = 0;
	for (const definitionId of params.invocationDefinitionIds) {
		const result = await db.delete(contextCache).where(and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.conversationId, params.conversationId), eq(contextCache.contextConfigId, params.contextConfigId), eq(contextCache.contextVariableKey, definitionId))).returning();
		totalRowsAffected += result.length;
	}
	return totalRowsAffected;
};
/**
* Get all cache entries for a conversation
*/
const getConversationCacheEntries = (db) => async (params) => {
	return (await db.query.contextCache.findMany({ where: and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.conversationId, params.conversationId)) })).map((entry) => ({
		...entry,
		value: entry.value
	}));
};
/**
* Get all cache entries for a context configuration
*/
const getContextConfigCacheEntries = (db) => async (params) => {
	return (await db.query.contextCache.findMany({ where: and(projectScopedWhere(contextCache, params.scopes), eq(contextCache.contextConfigId, params.contextConfigId)) })).map((entry) => ({
		...entry,
		value: entry.value
	}));
};

//#endregion
export { cleanupTenantCache, clearContextConfigCache, clearConversationCache, getCacheEntry, getContextConfigCacheEntries, getConversationCacheEntries, invalidateHeadersCache, invalidateInvocationDefinitionsCache, setCacheEntry };