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

//#region src/data-access/runtime/events.ts
const createEvent = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [inserted] = await db.insert(events).values({
		...params,
		createdAt: now,
		updatedAt: now
	}).onConflictDoNothing({ target: [
		events.tenantId,
		events.projectId,
		events.id
	] }).returning();
	if (inserted) return {
		row: inserted,
		conflict: false
	};
	const [existing] = await db.select().from(events).where(and(projectScopedWhere(events, {
		tenantId: params.tenantId,
		projectId: params.projectId
	}), eq(events.id, params.id))).limit(1);
	if (!existing) throw new Error(`createEvent: insert returned no row and no existing row found for id=${params.id}`);
	return {
		row: existing,
		conflict: true
	};
};
const getEventById = (db) => async (params) => {
	const [result] = await db.select().from(events).where(and(projectScopedWhere(events, params.scopes), eq(events.id, params.eventId))).limit(1);
	return result;
};
const listEventsByConversationId = (db) => async (params) => {
	const page = params.pagination?.page || 1;
	const limit = Math.min(params.pagination?.limit || 100, 100);
	const offset = (page - 1) * limit;
	return db.select().from(events).where(and(projectScopedWhere(events, params.scopes), eq(events.conversationId, params.conversationId))).orderBy(desc(events.createdAt)).limit(limit).offset(offset);
};
const deleteEventsByConversationIds = (db) => async (params) => {
	if (params.conversationIds.length === 0) return 0;
	return (await db.delete(events).where(and(projectScopedWhere(events, params.scopes), inArray(events.conversationId, params.conversationIds))).returning()).length;
};

//#endregion
export { createEvent, deleteEventsByConversationIds, getEventById, listEventsByConversationId };