import { manage_schema_exports } from "../../db/manage/manage-schema.js";
import { getLogger } from "../../utils/logger.js";
import { resolveProjectMainRefs } from "../../dolt/ref-helpers.js";
import { listProjectsMetadata } from "../runtime/projects.js";
import { deleteTriggersByRunAsUserId, removeUserFromProjectTriggerUsers } from "./triggers.js";
import { deleteScheduledTriggersByRunAsUserId } from "../runtime/scheduledTriggers.js";
import { withRef } from "../../dolt/ref-scope.js";
import { drizzle } from "drizzle-orm/node-postgres";

//#region src/data-access/manage/triggerCleanup.ts
const logger = getLogger("auth-cleanup");
async function cleanupUserTriggers(params) {
	const { tenantId, userId, runDb, manageDbPool } = params;
	const projects = await listProjectsMetadata(runDb)({ tenantId });
	if (projects.length === 0) return;
	await Promise.allSettled(projects.map(async (project) => {
		try {
			await deleteScheduledTriggersByRunAsUserId(runDb)({
				tenantId,
				projectId: project.id,
				runAsUserId: userId
			});
		} catch (err) {
			logger.error({
				tenantId,
				projectId: project.id,
				userId,
				error: err
			}, "Failed to clean up scheduled triggers for project");
		}
	}));
	const connection = await manageDbPool.connect();
	let resolvedRefs;
	try {
		resolvedRefs = await resolveProjectMainRefs(drizzle(connection, { schema: manage_schema_exports }))(tenantId, projects.map((p) => p.id));
	} finally {
		connection.release();
	}
	const results = await Promise.allSettled(resolvedRefs.map(({ projectId, ref }) => withRef(manageDbPool, ref, async (db) => {
		await deleteTriggersByRunAsUserId(db)({
			tenantId,
			projectId,
			runAsUserId: userId
		});
		await removeUserFromProjectTriggerUsers(db)({
			tenantId,
			projectId,
			userId
		});
	}, {
		commit: true,
		commitMessage: `Remove triggers for departing user ${userId}`
	})));
	for (let i = 0; i < results.length; i++) {
		const result = results[i];
		const { projectId } = resolvedRefs[i];
		if (result.status === "rejected") logger.error({
			tenantId,
			projectId,
			userId,
			error: result.reason
		}, "Failed to clean up webhook triggers for project");
	}
}

//#endregion
export { cleanupUserTriggers };