import { recordIndexerError } from "@open-mercato/shared/lib/indexers/error-log";
import { resolveEntityTableName } from "@open-mercato/shared/lib/query/engine";
import { sql } from "kysely";
import { markDeleted } from "../lib/indexer.js";
import { applyCoverageAdjustments, createCoverageAdjustments } from "../lib/coverage.js";
import { loadQueryIndexRowScope, resolveQueryIndexRecordScope } from "../lib/subscriber-scope.js";
const metadata = { event: "query_index.delete_one", persistent: false };
const DELETE_COVERAGE_THROTTLE_MS = 5 * 60 * 1e3;
const lastDeleteCoverageRefreshAt = /* @__PURE__ */ new Map();
function shouldAllowDeleteCoverageRefresh(entityType, tenantId) {
  if (!entityType) return false;
  const key = `${entityType}|${tenantId ?? "__null__"}`;
  const now = Date.now();
  const last = lastDeleteCoverageRefreshAt.get(key) ?? 0;
  if (now - last < DELETE_COVERAGE_THROTTLE_MS) return false;
  lastDeleteCoverageRefreshAt.set(key, now);
  return true;
}
async function handle(payload, ctx) {
  const baseEm = ctx.resolve("em");
  const em = typeof baseEm?.fork === "function" ? baseEm.fork() : baseEm;
  const entityType = String(payload?.entityType || "");
  const recordId = String(payload?.recordId || "");
  if (!entityType || !recordId) return;
  let organizationId = payload?.organizationId ?? null;
  let tenantId = payload?.tenantId ?? null;
  const coverageDelayMs = typeof payload?.coverageDelayMs === "number" ? payload.coverageDelayMs : void 0;
  try {
    const hasPayloadOrganizationId = Object.prototype.hasOwnProperty.call(payload ?? {}, "organizationId");
    const hasPayloadTenantId = Object.prototype.hasOwnProperty.call(payload ?? {}, "tenantId");
    const rowScope = await loadQueryIndexRowScope(em, entityType, recordId).catch(() => null);
    const resolvedScope = resolveQueryIndexRecordScope({
      payloadOrganizationId: payload?.organizationId,
      payloadTenantId: payload?.tenantId,
      hasPayloadOrganizationId,
      hasPayloadTenantId,
      rowScope
    });
    organizationId = resolvedScope.organizationId;
    tenantId = resolvedScope.tenantId;
    const { wasActive } = await markDeleted(em, { entityType, recordId, organizationId, tenantId });
    let baseDelta = 0;
    let baseCheckSucceeded = false;
    try {
      const db = em.getKysely();
      const table = resolveEntityTableName(em, entityType);
      const row = await db.selectFrom(table).select(["deleted_at"]).where("id", "=", recordId).where("organization_id", organizationId === null ? "is" : "=", organizationId).where(sql`tenant_id is not distinct from ${tenantId}`).executeTakeFirst();
      const baseMissing = !row;
      const baseDeleted = baseMissing || row && row.deleted_at != null;
      baseCheckSucceeded = true;
      if (baseDeleted) baseDelta = -1;
    } catch {
    }
    if (!baseCheckSucceeded) baseDelta = -1;
    const baseDeltaOverride = typeof payload?.coverageBaseDelta === "number" ? payload.coverageBaseDelta : void 0;
    const indexDeltaOverride = typeof payload?.coverageIndexDelta === "number" ? payload.coverageIndexDelta : void 0;
    let effectiveBaseDelta = baseDeltaOverride ?? baseDelta;
    let effectiveIndexDelta = indexDeltaOverride ?? (wasActive ? -1 : 0);
    if (!Number.isFinite(effectiveBaseDelta)) effectiveBaseDelta = 0;
    if (!Number.isFinite(effectiveIndexDelta)) effectiveIndexDelta = 0;
    if (effectiveBaseDelta !== 0 || effectiveIndexDelta !== 0) {
      const adjustments = createCoverageAdjustments({
        entityType,
        tenantId: tenantId ?? null,
        organizationId: organizationId ?? null,
        baseDelta: effectiveBaseDelta,
        indexDelta: effectiveIndexDelta
      });
      if (adjustments.length) {
        await applyCoverageAdjustments(em, adjustments);
      }
    }
    const suppressCoverage = payload?.suppressCoverage === true;
    const explicitDelayRequested = typeof payload?.coverageDelayMs === "number";
    const shouldRefreshCoverage = !suppressCoverage && (coverageDelayMs === void 0 || coverageDelayMs >= 0) && (explicitDelayRequested || shouldAllowDeleteCoverageRefresh(entityType, tenantId));
    const coverageRefreshDelay = coverageDelayMs ?? 0;
    void (async () => {
      try {
        const bus = ctx.resolve("eventBus");
        if (shouldRefreshCoverage) {
          await bus.emitEvent("query_index.coverage.refresh", {
            entityType,
            tenantId: tenantId ?? null,
            organizationId: organizationId ?? null,
            delayMs: coverageRefreshDelay
          });
        }
        await bus.emitEvent("search.delete_record", { entityId: entityType, recordId, organizationId, tenantId });
      } catch (error) {
        await recordIndexerError(
          { em },
          {
            source: "query_index",
            handler: "event:query_index.delete_one:coverage_search",
            error,
            entityType,
            recordId,
            tenantId: tenantId ?? null,
            organizationId: organizationId ?? null,
            payload
          }
        ).catch(() => {
        });
      }
    })();
  } catch (error) {
    await recordIndexerError(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.delete_one",
        error,
        entityType,
        recordId,
        tenantId: tenantId ?? null,
        organizationId: organizationId ?? null,
        payload
      }
    );
    throw error;
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=delete_one.js.map
