import { sql } from "kysely";
import { resolveSearchConfig } from "@open-mercato/shared/lib/search/config";
import { tokenizeText } from "@open-mercato/shared/lib/search/tokenize";
function getDb(em) {
  return em.getKysely();
}
async function findMessageIdsBySearchTokens({
  em,
  query,
  tenantId,
  organizationId,
  fields = ["subject", "body", "external_name"]
}) {
  const trimmed = query.trim();
  if (!trimmed) return null;
  const tokens = tokenizeText(trimmed, resolveSearchConfig());
  if (!tokens.hashes.length) return [];
  const db = getDb(em);
  let searchQuery = db.selectFrom("search_tokens").select("entity_id").where("entity_type", "=", "messages:message").where("field", "in", fields).where("token_hash", "in", tokens.hashes).where(sql`tenant_id is not distinct from ${tenantId}`);
  if (organizationId) {
    searchQuery = searchQuery.where("organization_id", "=", organizationId);
  } else {
    searchQuery = searchQuery.where(sql`organization_id is not distinct from ${null}`);
  }
  const rows = await searchQuery.groupBy("entity_id").having(sql`count(distinct token_hash) >= ${tokens.hashes.length}`).execute();
  return rows.map((row) => typeof row.entity_id === "string" ? row.entity_id : null).filter((id) => typeof id === "string" && id.length > 0);
}
export {
  findMessageIdsBySearchTokens
};
//# sourceMappingURL=searchLookup.js.map
