import { sql } from "kysely";
import { TERMINAL_INTERACTION_STATUS_LIST } from "./interactionStatus.js";
async function recomputeNextInteraction(em, entityId, organizationId) {
  const db = em.getKysely();
  let query = db.selectFrom("customer_interactions").select([
    "id",
    "scheduled_at",
    "title",
    "interaction_type",
    "appearance_icon",
    "appearance_color"
  ]).where("entity_id", "=", entityId).where("status", "not in", [...TERMINAL_INTERACTION_STATUS_LIST]).where("scheduled_at", "is not", null).where("deleted_at", "is", null);
  if (organizationId) {
    query = query.where("organization_id", "=", organizationId);
  }
  const candidate = await query.orderBy("scheduled_at", "asc").orderBy(sql`priority desc nulls last`).orderBy("created_at", "asc").orderBy("id", "asc").executeTakeFirst();
  if (candidate) {
    const interactionName = candidate.title && candidate.title.trim() !== "" ? candidate.title : candidate.interaction_type;
    await db.updateTable("customer_entities").set({
      next_interaction_at: candidate.scheduled_at,
      next_interaction_name: interactionName,
      next_interaction_ref_id: candidate.id,
      next_interaction_icon: candidate.appearance_icon,
      next_interaction_color: candidate.appearance_color,
      updated_at: sql`now()`
    }).where("id", "=", entityId).execute();
    return { nextInteractionId: String(candidate.id) };
  } else {
    await db.updateTable("customer_entities").set({
      next_interaction_at: null,
      next_interaction_name: null,
      next_interaction_ref_id: null,
      next_interaction_icon: null,
      next_interaction_color: null,
      updated_at: sql`now()`
    }).where("id", "=", entityId).execute();
    return { nextInteractionId: null };
  }
}
export {
  recomputeNextInteraction
};
//# sourceMappingURL=interactionProjection.js.map
