import { BasicQueryEngine, resolveEntityTableName } from "@open-mercato/shared/lib/query/engine";
import { HybridQueryEngine } from "./lib/engine.js";
function toEntityTypeFromEvent(event) {
  const parts = event.split(".");
  if (parts.length !== 3) return null;
  const [mod, ent] = parts;
  return `${mod}:${ent}`;
}
function register(container) {
  try {
    const em = container.resolve("em");
    const basic = new BasicQueryEngine(
      em,
      void 0,
      () => {
        try {
          return container.resolve("tenantEncryptionService");
        } catch {
          return null;
        }
      }
    );
    const hybrid = new HybridQueryEngine(
      em,
      basic,
      () => {
        try {
          return container.resolve("eventBus");
        } catch {
          return null;
        }
      },
      () => {
        try {
          return container.resolve("vectorIndexService");
        } catch {
          return null;
        }
      },
      () => {
        try {
          return container.resolve("tenantEncryptionService");
        } catch {
          return null;
        }
      }
    );
    container.register({ queryEngine: { resolve: () => hybrid } });
  } catch {
  }
  const setup = () => {
    let bus;
    try {
      bus = container.resolve("eventBus");
    } catch {
      bus = null;
    }
    if (!bus) {
      setTimeout(setup, 0);
      return;
    }
    const makeUpsertHandler = (entityType) => async (payload, ctx) => {
      try {
        const em = ctx.resolve("em");
        let orgId = payload?.organizationId || payload?.orgId || ctx?.organizationId || null;
        let tenantId = payload?.tenantId || ctx?.tenantId || null;
        const id = String(payload?.id || payload?.recordId || "");
        if (!id) return;
        if (!orgId || !tenantId) {
          try {
            const db = em.getKysely();
            const table = resolveEntityTableName(em, entityType);
            const row = await db.selectFrom(table).select(["organization_id", "tenant_id"]).where("id", "=", id).executeTakeFirst();
            orgId = row?.organization_id ?? orgId;
            tenantId = row?.tenant_id ?? tenantId;
          } catch {
          }
        }
        try {
          const db = em.getKysely();
          let cfQuery = db.selectFrom("custom_field_defs").select(["id"]).where("entity_id", "=", entityType).where("is_active", "=", true);
          if (orgId != null) {
            cfQuery = cfQuery.where((eb) => eb.or([
              eb("organization_id", "=", orgId),
              eb("organization_id", "is", null)
            ]));
          } else {
            cfQuery = cfQuery.where("organization_id", "is", null);
          }
          if (tenantId != null) {
            cfQuery = cfQuery.where((eb) => eb.or([
              eb("tenant_id", "=", tenantId),
              eb("tenant_id", "is", null)
            ]));
          } else {
            cfQuery = cfQuery.where("tenant_id", "is", null);
          }
          const hasCf = await cfQuery.executeTakeFirst();
          if (!hasCf) return;
        } catch {
        }
        try {
          const bus2 = ctx.resolve("eventBus");
          await bus2.emitEvent("query_index.upsert_one", { entityType, recordId: id, organizationId: orgId, tenantId });
        } catch {
        }
      } catch {
      }
    };
    const makeDeleteHandler = (entityType) => async (payload, ctx) => {
      try {
        const em = ctx.resolve("em");
        let orgId = payload?.organizationId || payload?.orgId || ctx?.organizationId || null;
        let tenantId = payload?.tenantId || ctx?.tenantId || null;
        const id = String(payload?.id || payload?.recordId || "");
        if (!id) return;
        if (!orgId || !tenantId) {
          try {
            const db = em.getKysely();
            const table = resolveEntityTableName(em, entityType);
            const row = await db.selectFrom(table).select(["organization_id", "tenant_id"]).where("id", "=", id).executeTakeFirst();
            orgId = row?.organization_id ?? orgId;
            tenantId = row?.tenant_id ?? tenantId;
          } catch {
          }
        }
        try {
          const bus2 = ctx.resolve("eventBus");
          await bus2.emitEvent("query_index.delete_one", { entityType, recordId: id, organizationId: orgId, tenantId });
        } catch {
        }
      } catch {
      }
    };
    try {
      const em = container.resolve("em");
      const db = em.getKysely();
      const cfEntityIds = [];
      db.selectFrom("custom_field_defs").select(["entity_id"]).distinct().execute().then((rows) => {
        for (const r of rows || []) cfEntityIds.push(String(r.entity_id));
      }).catch(() => {
      }).finally(() => {
        const proceed = (ids) => {
          for (const entityType of Array.from(new Set(ids))) {
            const [mod, ent] = entityType.split(":");
            if (!mod || !ent) continue;
            bus.on(`${mod}.${ent}.created`, makeUpsertHandler(entityType), { moduleId: "query_index" });
            bus.on(`${mod}.${ent}.updated`, makeUpsertHandler(entityType), { moduleId: "query_index" });
            bus.on(`${mod}.${ent}.deleted`, makeDeleteHandler(entityType), { moduleId: "query_index" });
          }
        };
        if (cfEntityIds.length > 0) {
          proceed(cfEntityIds);
        } else {
          import("../../generated/entities.ids.generated.js").then((core) => {
            const flatten = (E) => Object.values(E || {}).flatMap((o) => Object.values(o || {}));
            const guesses = /* @__PURE__ */ new Set([...flatten(core.E)]);
            proceed(Array.from(guesses));
          }).catch(() => {
          });
        }
      });
    } catch {
    }
  };
  try {
    setup();
  } catch {
  }
}
export {
  register
};
//# sourceMappingURL=di.js.map
