import { resolveKyselyClient } from "./kysely.js";
const STUCK_DEFAULT_THRESHOLD_DAYS = 14;
const DAY_MS = 24 * 60 * 60 * 1e3;
async function fetchStuckThresholdDays(db, organizationId, tenantId) {
  const row = await db.selectFrom("customer_settings").select(["stuck_threshold_days"]).where("organization_id", "=", organizationId).where("tenant_id", "=", tenantId).executeTakeFirst();
  const raw = row?.stuck_threshold_days;
  const value = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : null;
  if (value !== null && Number.isFinite(value) && value > 0) return value;
  return STUCK_DEFAULT_THRESHOLD_DAYS;
}
async function fetchStuckDealIds(em, organizationId, tenantId) {
  const db = resolveKyselyClient(em);
  if (!db) return [];
  const threshold = await fetchStuckThresholdDays(db, organizationId, tenantId);
  const cutoff = new Date(Date.now() - threshold * DAY_MS);
  const oldTransitionRows = await db.selectFrom("customer_deal_stage_transitions").select(["deal_id"]).select((eb) => eb.fn.max("transitioned_at").as("last_transition")).where("organization_id", "=", organizationId).where("tenant_id", "=", tenantId).where("deleted_at", "is", null).groupBy("deal_id").having((eb) => eb(eb.fn.max("transitioned_at"), "<", cutoff)).execute();
  const transitionedDealIds = await db.selectFrom("customer_deal_stage_transitions").select(["deal_id"]).distinct().where("organization_id", "=", organizationId).where("tenant_id", "=", tenantId).where("deleted_at", "is", null).execute();
  const transitionedSet = new Set(transitionedDealIds.map((r) => r.deal_id));
  const oldUntransitionedDeals = await db.selectFrom("customer_deals").select(["id"]).where("organization_id", "=", organizationId).where("tenant_id", "=", tenantId).where("deleted_at", "is", null).where("created_at", "<", cutoff).execute();
  const result = /* @__PURE__ */ new Set();
  oldTransitionRows.forEach((row) => result.add(row.deal_id));
  oldUntransitionedDeals.forEach((row) => {
    if (!transitionedSet.has(row.id)) result.add(row.id);
  });
  return Array.from(result);
}
export {
  STUCK_DEFAULT_THRESHOLD_DAYS,
  fetchStuckDealIds,
  fetchStuckThresholdDays
};
//# sourceMappingURL=stuckDeals.js.map
