import runDbClient_default from "../../../data/db/runDbClient.js";
import { isEntityChanged } from "../../../utils/entityDiff.js";
import { OrgRoles, canUseProjectStrict, createApiError, getOrganizationMemberByUserId } from "@inkeep/agents-core";

//#region src/domains/manage/routes/triggerHelpers.ts
const INVALID_RUN_AS_USER = "Invalid runAsUserId: user not found or does not have permission on this project";
async function validateRunAsUserId(params) {
	const { runAsUserId, callerId, tenantId, projectId, tenantRole } = params;
	if (runAsUserId === "system" || runAsUserId.startsWith("apikey:")) throw createApiError({
		code: "bad_request",
		message: "runAsUserId must be a real user ID, not a system identifier"
	});
	const isAdmin = tenantRole === OrgRoles.OWNER || tenantRole === OrgRoles.ADMIN;
	if (runAsUserId !== callerId && !isAdmin) throw createApiError({
		code: "forbidden",
		message: "Only org admins or owners can set runAsUserId to a different user. Regular users can only set runAsUserId to themselves."
	});
	if (!await getOrganizationMemberByUserId(runDbClient_default)(tenantId, runAsUserId)) throw createApiError({
		code: "bad_request",
		message: INVALID_RUN_AS_USER
	});
	if (!await canUseProjectStrict({
		userId: runAsUserId,
		tenantId,
		projectId
	})) throw createApiError({
		code: "bad_request",
		message: INVALID_RUN_AS_USER
	});
}
/**
* Check if a non-admin user is allowed to mutate a trigger.
* Admins can mutate any trigger. Non-admins can only mutate triggers they created or that run as them.
*/
function assertCanMutateTrigger(params) {
	const { trigger, callerId, tenantRole } = params;
	if (tenantRole === OrgRoles.OWNER || tenantRole === OrgRoles.ADMIN) return;
	if (trigger.createdBy === callerId || trigger.runAsUserId === callerId) return;
	throw createApiError({
		code: "forbidden",
		message: "You can only modify triggers that you created or that are configured to run as you."
	});
}
async function validateTriggerPermissions(params) {
	const { triggerData, existing, callerId, tenantId, projectId, tenantRole } = params;
	if (existing) {
		if (!isEntityChanged(triggerData, existing)) return;
		assertCanMutateTrigger({
			trigger: existing,
			callerId,
			tenantRole
		});
		if (triggerData.runAsUserId !== existing.runAsUserId && triggerData.runAsUserId) await validateRunAsUserId({
			runAsUserId: triggerData.runAsUserId,
			callerId,
			tenantId,
			projectId,
			tenantRole
		});
	} else {
		if (triggerData.runAsUserId) await validateRunAsUserId({
			runAsUserId: triggerData.runAsUserId,
			callerId,
			tenantId,
			projectId,
			tenantRole
		});
		triggerData.createdBy = callerId;
	}
}

//#endregion
export { assertCanMutateTrigger, validateRunAsUserId, validateTriggerPermissions };