import { sql } from "kysely";
import { resolveSearchConfig } from "./config.js";
import { tokenizeText } from "./tokenize.js";
async function findEntityIdsBySearchTokens({
  db,
  entityType,
  query,
  fields,
  scope,
  config
}) {
  const trimmed = query.trim();
  if (!trimmed) return { matched: false, reason: "empty-query" };
  const searchConfig = config ?? resolveSearchConfig();
  if (!searchConfig.enabled) return { matched: false, reason: "search-disabled" };
  const { hashes } = tokenizeText(trimmed, searchConfig);
  if (!hashes.length) return { matched: false, reason: "no-tokens" };
  let builder = db.selectFrom("search_tokens").select("entity_id").where("entity_type", "=", entityType).where("token_hash", "in", hashes);
  const scopedFields = (fields ?? []).filter((field) => typeof field === "string" && field.length > 0);
  if (scopedFields.length === 1) {
    builder = builder.where("field", "=", scopedFields[0]);
  } else if (scopedFields.length > 1) {
    builder = builder.where("field", "in", Array.from(scopedFields));
  }
  if (scope?.tenantId !== void 0) {
    builder = builder.where(sql`tenant_id is not distinct from ${scope.tenantId}`);
  }
  if (scope?.organizationId !== void 0) {
    builder = scope.organizationId === null ? builder.where(sql`organization_id is not distinct from ${null}`) : builder.where("organization_id", "=", scope.organizationId);
  } else if (scope?.organizationIds?.length) {
    builder = builder.where("organization_id", "in", Array.from(scope.organizationIds));
  }
  const rows = await builder.groupBy("entity_id").having(sql`count(distinct token_hash) >= ${hashes.length}`).execute();
  const ids = rows.map((row) => typeof row.entity_id === "string" ? row.entity_id : null).filter((id) => typeof id === "string" && id.length > 0);
  return { matched: true, ids };
}
async function findEntityIdsBySearchTokensCompat(input) {
  const result = await findEntityIdsBySearchTokens(input);
  if (result.matched) return result.ids;
  return result.reason === "empty-query" ? null : [];
}
export {
  findEntityIdsBySearchTokens,
  findEntityIdsBySearchTokensCompat
};
//# sourceMappingURL=tokenLookup.js.map
