import { sql } from "kysely";
import { prepareJob, updateJobProgress, finalizeJob } from "./jobs.js";
async function purgeIndexScope(em, options) {
  const db = em.getKysely();
  const scope = {
    entityType: options.entityType,
    organizationId: options.organizationId ?? null,
    tenantId: options.tenantId ?? null,
    partitionIndex: null,
    partitionCount: null
  };
  const applyScope = (q) => {
    let chain = q.where("entity_type", "=", options.entityType);
    if (options.organizationId !== void 0) {
      chain = chain.where(sql`organization_id is not distinct from ${options.organizationId ?? null}`);
    }
    if (options.tenantId !== void 0) {
      chain = chain.where(sql`tenant_id is not distinct from ${options.tenantId ?? null}`);
    }
    return chain;
  };
  const totalRow = await applyScope(
    db.selectFrom("entity_indexes").select(sql`count(*)`.as("count"))
  ).executeTakeFirst();
  const total = totalRow ? Number(totalRow.count) || 0 : 0;
  await prepareJob(db, scope, "purging", { totalCount: total });
  if (total > 0) {
    const result = await applyScope(
      db.deleteFrom("entity_indexes")
    ).executeTakeFirst();
    const removed = Number(result?.numDeletedRows ?? 0);
    await updateJobProgress(db, scope, removed || total);
  } else {
    await updateJobProgress(db, scope, 0);
  }
  await finalizeJob(db, scope);
}
export {
  purgeIndexScope
};
//# sourceMappingURL=purge.js.map
