import { recordIndexerError } from "@open-mercato/shared/lib/indexers/error-log";
import { upsertIndexRow, reindexSearchTokensForRecord } from "../lib/indexer.js";
import { applyCoverageAdjustments, createCoverageAdjustments } from "../lib/coverage.js";
import { loadQueryIndexRowScope, resolveQueryIndexRecordScope } from "../lib/subscriber-scope.js";
const metadata = { event: "query_index.upsert_one", persistent: false };
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 suppressCoverage = payload?.suppressCoverage === true;
  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 searchTokenDoc = typeof payload?.searchTokenDoc === "object" && payload.searchTokenDoc && !Array.isArray(payload.searchTokenDoc) ? payload.searchTokenDoc : null;
    const result = await upsertIndexRow(em, {
      entityType,
      recordId,
      organizationId,
      tenantId,
      searchTokenDoc,
      deferSearchTokens: true
    });
    if (!suppressCoverage) {
      const doc = result.doc;
      const isActive = !!doc && (doc.deleted_at == null || doc.deleted_at === null);
      let baseDelta = typeof payload?.coverageBaseDelta === "number" ? payload.coverageBaseDelta : void 0;
      let indexDelta = typeof payload?.coverageIndexDelta === "number" ? payload.coverageIndexDelta : void 0;
      const crudAction = typeof payload?.crudAction === "string" ? payload.crudAction : void 0;
      if (baseDelta === void 0) {
        if (result.revived) baseDelta = 1;
        else if (crudAction === "created") baseDelta = 1;
        else baseDelta = 0;
      }
      if (indexDelta === void 0) {
        if (isActive && (result.created || result.revived)) indexDelta = 1;
        else indexDelta = 0;
      }
      if (!isActive && baseDelta > 0) baseDelta = 0;
      if (!isActive && indexDelta > 0) indexDelta = 0;
      if (!Number.isFinite(baseDelta)) baseDelta = 0;
      if (!Number.isFinite(indexDelta)) indexDelta = 0;
      const adjustments = createCoverageAdjustments({
        entityType,
        tenantId: tenantId ?? null,
        organizationId: organizationId ?? null,
        baseDelta,
        indexDelta
      });
      if (adjustments.length) {
        await applyCoverageAdjustments(em, adjustments);
      }
      if (coverageDelayMs !== void 0 && coverageDelayMs >= 0) {
        try {
          const bus = ctx.resolve("eventBus");
          await bus.emitEvent("query_index.coverage.refresh", {
            entityType,
            tenantId: tenantId ?? null,
            organizationId: organizationId ?? null,
            delayMs: coverageDelayMs
          });
        } catch {
        }
      }
    }
    const deferredScope = { entityType, recordId, organizationId, tenantId };
    const resolvedDoc = result.doc;
    void (async () => {
      try {
        await reindexSearchTokensForRecord(em, { ...deferredScope, doc: resolvedDoc, searchTokenDoc });
        const bus = ctx.resolve("eventBus");
        await bus.emitEvent("query_index.vectorize_one", deferredScope);
        await bus.emitEvent("search.index_record", { entityId: entityType, recordId, organizationId, tenantId });
      } catch (error) {
        await recordIndexerError(
          { em },
          {
            source: "query_index",
            handler: "event:query_index.upsert_one:search_tokens",
            error,
            entityType,
            recordId,
            tenantId: tenantId ?? null,
            organizationId: organizationId ?? null,
            payload
          }
        ).catch(() => {
        });
      }
    })();
  } catch (error) {
    await recordIndexerError(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.upsert_one",
        error,
        entityType,
        recordId,
        tenantId: tenantId ?? null,
        organizationId: organizationId ?? null,
        payload
      }
    );
    throw error;
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=upsert_one.js.map
