/**
 * Query preprocessor for FTS5 search queries.
 *
 * Normalizes raw user input into an FTS5-compatible MATCH expression
 * with prefix wildcard expansion on the last token.
 */

/**
 * Preprocess a raw search query string for FTS5 MATCH.
 *
 * Steps:
 * 1. Trim and normalize internal whitespace.
 * 2. Strip FTS5 grouping characters `(` and `)` that would cause parse errors.
 * 3. Append a prefix wildcard `*` to the last token when it is >= 3 characters
 *    and does not already end with `*`. This gives a "typing as you go" feel.
 */
export function preprocessQuery(raw: string): string {
	// 1. Trim and collapse whitespace.
	let q = raw.trim().replace(/\s+/g, ' ');

	// 2. Remove parentheses (not valid in simple FTS5 queries without explicit operators).
	q = q.replace(/[()]/g, ' ').replace(/\s+/g, ' ').trim();

	if (!q) return q;

	// 3. Add prefix wildcard to the last token.
	const tokens = q.split(' ');
	const lastToken = tokens.at(-1) ?? '';
	if (lastToken.length >= 3 && !lastToken.endsWith('*')) {
		tokens[tokens.length - 1] = lastToken + '*';
	}

	return tokens.join(' ');
}
