import { triggerInvocations } from "../../db/runtime/runtime-schema.js";
import { agentScopedWhere } from "../manage/scope-helpers.js";
import { and, count, desc, eq, gte, lte } from "drizzle-orm";

//#region src/data-access/runtime/triggerInvocations.ts
/**
* Get a trigger invocation by ID (agent-scoped)
*/
const getTriggerInvocationById = (db) => async (params) => {
	return await db.query.triggerInvocations.findFirst({ where: and(agentScopedWhere(triggerInvocations, params.scopes), eq(triggerInvocations.triggerId, params.triggerId), eq(triggerInvocations.id, params.invocationId)) });
};
/**
* List trigger invocations with optional filtering (agent-scoped)
*/
const listTriggerInvocationsPaginated = (db) => async (params) => {
	const page = params.pagination?.page || 1;
	const limit = Math.min(params.pagination?.limit || 10, 100);
	const offset = (page - 1) * limit;
	const conditions = [agentScopedWhere(triggerInvocations, params.scopes), eq(triggerInvocations.triggerId, params.triggerId)];
	if (params.filters?.status) conditions.push(eq(triggerInvocations.status, params.filters.status));
	if (params.filters?.from) conditions.push(gte(triggerInvocations.createdAt, params.filters.from));
	if (params.filters?.to) conditions.push(lte(triggerInvocations.createdAt, params.filters.to));
	const whereClause = and(...conditions);
	const [data, totalResult] = await Promise.all([db.select().from(triggerInvocations).where(whereClause).limit(limit).offset(offset).orderBy(desc(triggerInvocations.createdAt)), db.select({ count: count() }).from(triggerInvocations).where(whereClause)]);
	const total = totalResult[0]?.count || 0;
	return {
		data,
		pagination: {
			page,
			limit,
			total,
			pages: Math.ceil(total / limit)
		}
	};
};
/**
* Create a new trigger invocation (agent-scoped)
*/
const createTriggerInvocation = (db) => async (params) => {
	return (await db.insert(triggerInvocations).values(params).returning())[0];
};
/**
* Update trigger invocation status (agent-scoped)
*/
const updateTriggerInvocationStatus = (db) => async (params) => {
	return (await db.update(triggerInvocations).set(params.data).where(and(agentScopedWhere(triggerInvocations, params.scopes), eq(triggerInvocations.triggerId, params.triggerId), eq(triggerInvocations.id, params.invocationId))).returning())[0];
};

//#endregion
export { createTriggerInvocation, getTriggerInvocationById, listTriggerInvocationsPaginated, updateTriggerInvocationStatus };