import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { cancelPastPendingInvocationsForTrigger, cancelPendingInvocationsForTrigger } from "@inkeep/agents-core";

//#region src/domains/run/services/ScheduledTriggerService.ts
/**
* Service for managing scheduled trigger lifecycle side effects.
*
* With the manage-table approach, next_run_at is set directly on the
* scheduled_triggers table in the manage DB. This service only handles
* cancellation of stale invocations when triggers are re-enabled or rescheduled.
*/
const logger = getLogger$1("ScheduledTriggerService");
async function onTriggerUpdated(params) {
	const { trigger, previousEnabled, scheduleChanged } = params;
	if (!previousEnabled && !trigger.enabled) return;
	if (!previousEnabled && trigger.enabled) {
		const cancelledCount = await cancelPastPendingInvocationsForTrigger(runDbClient_default)({
			scopes: {
				tenantId: trigger.tenantId,
				projectId: trigger.projectId,
				agentId: trigger.agentId
			},
			scheduledTriggerId: trigger.id
		});
		if (cancelledCount > 0) logger.info({
			scheduledTriggerId: trigger.id,
			cancelledCount
		}, "Cancelled past pending invocations on trigger re-enable");
		return;
	}
	if (scheduleChanged) {
		const cancelledCount = await cancelPendingInvocationsForTrigger(runDbClient_default)({
			scopes: {
				tenantId: trigger.tenantId,
				projectId: trigger.projectId,
				agentId: trigger.agentId
			},
			scheduledTriggerId: trigger.id
		});
		if (cancelledCount > 0) logger.info({
			scheduledTriggerId: trigger.id,
			cancelledCount
		}, "Cancelled pending invocations on schedule change");
	}
}

//#endregion
export { onTriggerUpdated };