/** tsquery metacharacters that must not reach Postgres `to_tsquery` / `plainto_tsquery`. */
const TSQUERY_METACHAR_RE = /[!&|():*'"`<>\\]/g

/**
 * Sanitize user input for prefix tsquery (`token:* & …`).
 * Strips metachars, AND-joins prefix tokens.
 *
 * SECURITY (shared host contract): the output is injection-safe end-to-end ONLY if
 * the host passes it to `to_tsquery()`/`plainto_tsquery()` or a bound parameter, and
 * NEVER string-interpolates it into raw SQL. `websearch_to_tsquery` is the throw-proof
 * alternative. See `packages/util/src/fts/README.md`.
 */
export function sanitizeTsquery(input: string): string {
  const cleaned = input.replace(TSQUERY_METACHAR_RE, ' ').trim()
  if (!cleaned) return ''
  const tokens = cleaned.split(/\s+/).filter(Boolean)
  if (tokens.length === 0) return ''
  return tokens.map((token) => `${token}:*`).join(' & ')
}
