import { scheduledTriggerUsers, scheduledTriggers } from "../../db/runtime/runtime-schema.js";
import { and, asc, count, eq, inArray } from "drizzle-orm";

//#region src/data-access/runtime/scheduledTriggerUsers.ts
const getScheduledTriggerUsers = (db) => async (params) => {
	return await db.select().from(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), eq(scheduledTriggerUsers.scheduledTriggerId, params.scheduledTriggerId))).orderBy(asc(scheduledTriggerUsers.createdAt));
};
const createScheduledTriggerUser = (db) => async (params) => {
	return (await db.insert(scheduledTriggerUsers).values({
		tenantId: params.tenantId,
		scheduledTriggerId: params.scheduledTriggerId,
		userId: params.userId
	}).onConflictDoNothing().returning())[0];
};
const deleteScheduledTriggerUser = (db) => async (params) => {
	await db.delete(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), eq(scheduledTriggerUsers.scheduledTriggerId, params.scheduledTriggerId), eq(scheduledTriggerUsers.userId, params.userId)));
};
const setScheduledTriggerUsers = (db) => async (params) => {
	await db.transaction(async (tx) => {
		await tx.delete(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), eq(scheduledTriggerUsers.scheduledTriggerId, params.scheduledTriggerId)));
		if (params.userIds.length > 0) await tx.insert(scheduledTriggerUsers).values(params.userIds.map((userId) => ({
			tenantId: params.tenantId,
			scheduledTriggerId: params.scheduledTriggerId,
			userId
		})));
	});
};
const getScheduledTriggerUserCount = (db) => async (params) => {
	return (await db.select({ count: count() }).from(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), eq(scheduledTriggerUsers.scheduledTriggerId, params.scheduledTriggerId))))[0]?.count ?? 0;
};
const getTriggerIdsWithUser = (db) => async (params) => {
	return db.select({ id: scheduledTriggers.id }).from(scheduledTriggers).innerJoin(scheduledTriggerUsers, and(eq(scheduledTriggerUsers.tenantId, scheduledTriggers.tenantId), eq(scheduledTriggerUsers.scheduledTriggerId, scheduledTriggers.id))).where(and(eq(scheduledTriggers.tenantId, params.tenantId), eq(scheduledTriggers.projectId, params.projectId), eq(scheduledTriggerUsers.userId, params.userId)));
};
const removeUserFromProjectScheduledTriggers = (db) => async (params) => {
	await db.transaction(async (tx) => {
		const triggerIdsWithUser = await getTriggerIdsWithUser(tx)(params);
		if (triggerIdsWithUser.length === 0) return;
		const triggerIds = triggerIdsWithUser.map((t) => t.id);
		await tx.delete(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), inArray(scheduledTriggerUsers.scheduledTriggerId, triggerIds), eq(scheduledTriggerUsers.userId, params.userId)));
		const triggersWithRemainingUsers = await tx.select({ triggerId: scheduledTriggerUsers.scheduledTriggerId }).from(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), inArray(scheduledTriggerUsers.scheduledTriggerId, triggerIds))).groupBy(scheduledTriggerUsers.scheduledTriggerId);
		const triggerIdsWithRemainingUsers = new Set(triggersWithRemainingUsers.map((r) => r.triggerId));
		const emptyTriggerIds = triggerIds.filter((id) => !triggerIdsWithRemainingUsers.has(id));
		if (emptyTriggerIds.length > 0) await tx.update(scheduledTriggers).set({
			enabled: false,
			updatedAt: (/* @__PURE__ */ new Date()).toISOString()
		}).where(and(eq(scheduledTriggers.tenantId, params.tenantId), inArray(scheduledTriggers.id, emptyTriggerIds), eq(scheduledTriggers.enabled, true)));
	});
};
const getScheduledTriggerUsersBatch = (db) => async (params) => {
	if (params.scheduledTriggerIds.length === 0) return /* @__PURE__ */ new Map();
	const rows = await db.select().from(scheduledTriggerUsers).where(and(eq(scheduledTriggerUsers.tenantId, params.tenantId), inArray(scheduledTriggerUsers.scheduledTriggerId, params.scheduledTriggerIds))).orderBy(asc(scheduledTriggerUsers.createdAt));
	const result = /* @__PURE__ */ new Map();
	for (const id of params.scheduledTriggerIds) result.set(id, []);
	for (const row of rows) {
		const users = result.get(row.scheduledTriggerId);
		if (users) users.push(row.userId);
	}
	return result;
};

//#endregion
export { createScheduledTriggerUser, deleteScheduledTriggerUser, getScheduledTriggerUserCount, getScheduledTriggerUsers, getScheduledTriggerUsersBatch, getTriggerIdsWithUser, removeUserFromProjectScheduledTriggers, setScheduledTriggerUsers };