import { AiPendingActionRepository } from "../data/repositories/AiPendingActionRepository.js";
import { emitAiAssistantEvent } from "../events.js";
const CANCELLED_EVENT_ID = "ai.action.cancelled";
const EXPIRED_EVENT_ID = "ai.action.expired";
const defaultCancelEmitter = async (eventId, payload) => {
  await emitAiAssistantEvent(eventId, payload, {
    persistent: true
  });
};
async function emitEventSafe(emitter, eventId, payload) {
  try {
    await emitter(eventId, payload);
  } catch (error) {
    console.warn(`[AI Pending Action] Failed to emit ${eventId}:`, error);
  }
}
async function executePendingActionCancel(input) {
  const { action, ctx, now } = input;
  const repo = input.repo ?? new AiPendingActionRepository(ctx.container.resolve("em"));
  const scope = {
    tenantId: ctx.tenantId,
    organizationId: ctx.organizationId,
    userId: ctx.userId
  };
  const clock = now ?? /* @__PURE__ */ new Date();
  const emitter = input.emitEvent ?? defaultCancelEmitter;
  if (action.status === "cancelled") {
    return { row: action, status: "cancelled" };
  }
  const expiresAt = action.expiresAt instanceof Date ? action.expiresAt : new Date(action.expiresAt);
  if (expiresAt.getTime() <= clock.getTime()) {
    const expiredRow = await repo.setStatus(action.id, "expired", scope, { now: clock });
    const resolvedAtIso = (expiredRow.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString();
    const expiresAtIso = (expiresAt ?? clock).toISOString?.() ?? new Date(clock).toISOString();
    const expiredPayload = {
      pendingActionId: expiredRow.id,
      agentId: expiredRow.agentId,
      toolName: expiredRow.toolName,
      status: expiredRow.status,
      tenantId: ctx.tenantId,
      organizationId: ctx.organizationId ?? null,
      userId: ctx.userId,
      resolvedByUserId: null,
      resolvedAt: resolvedAtIso,
      expiresAt: expiresAtIso,
      expiredAt: resolvedAtIso
    };
    await emitEventSafe(emitter, EXPIRED_EVENT_ID, expiredPayload);
    return { row: expiredRow, status: "expired" };
  }
  const trimmedReason = typeof input.reason === "string" ? input.reason.trim() : "";
  const executionResult = {
    error: {
      code: "cancelled_by_user",
      message: trimmedReason.length > 0 ? trimmedReason : "Cancelled by user"
    }
  };
  const cancelledRow = await repo.setStatus(action.id, "cancelled", scope, {
    resolvedByUserId: ctx.userId,
    executionResult,
    now: clock
  });
  const cancelledPayload = {
    pendingActionId: cancelledRow.id,
    agentId: cancelledRow.agentId,
    toolName: cancelledRow.toolName,
    status: cancelledRow.status,
    tenantId: ctx.tenantId,
    organizationId: ctx.organizationId ?? null,
    userId: ctx.userId,
    resolvedByUserId: ctx.userId,
    resolvedAt: (cancelledRow.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString(),
    executionResult,
    ...trimmedReason.length > 0 ? { reason: trimmedReason } : {}
  };
  await emitEventSafe(emitter, CANCELLED_EVENT_ID, cancelledPayload);
  return { row: cancelledRow, status: "cancelled" };
}
const PENDING_ACTION_CANCELLED_EVENT_ID = CANCELLED_EVENT_ID;
const PENDING_ACTION_EXPIRED_EVENT_ID = EXPIRED_EVENT_ID;
export {
  PENDING_ACTION_CANCELLED_EVENT_ID,
  PENDING_ACTION_EXPIRED_EVENT_ID,
  executePendingActionCancel
};
//# sourceMappingURL=pending-action-cancel.js.map
