/**
 * buildTsquery — search-completeness spec §6.1.
 *
 * Converts a raw user query string into a Postgres tsquery expression with
 * prefix matching (:*) on each token. Strips all tsquery metacharacters to
 * prevent injection.
 *
 * Example: buildTsquery('inv (foo)') → 'inv:* & foo:*'
 * Example: buildTsquery('  ') → ''  (caller should treat as no-match)
 */
export function buildTsquery(raw: string): string {
  // Strip characters special to tsquery: ! & | ( ) : * ' " \
  const safe = raw.replace(/[!&|():*'"\\]/g, ' ').trim()
  // Split on whitespace and filter empty strings
  const tokens = safe.split(/\s+/).filter(Boolean)
  if (tokens.length === 0) return ''
  // Append :* for prefix matching on each token, join with AND
  return tokens.map((t) => `${t}:*`).join(' & ')
}
