import { sql } from 'drizzle-orm';

export interface DealTextPredicateInput {
  q?: string;
  locale?: string;
  searchConfig?: string; // regconfig from getLanguageCached(locale).searchConfig; undefined => ILIKE fallback
}

/**
 * Returns a BARE SQL condition (NO leading `AND`) matching deals (alias `d`) against the text query,
 * or null when there is no query. Callers prefix per their own SQL builder:
 *   - facets CTE: sql`AND ${pred}`
 *   - runSearch:  if (pred) filters.push(pred)   // into the and(...) array
 * MUST be the only place this predicate is built (Invariant I1).
 */
export function buildDealTextPredicate(input: DealTextPredicateInput) {
  const q = input.q?.trim() ?? '';
  if (!q) return null;
  if (input.searchConfig && input.locale) {
    const cfg = input.searchConfig;
    const loc = input.locale;
    return sql`EXISTS (
      SELECT 1 FROM deal_translations t
      WHERE t.deal_id = d.id
        AND t.locale = ${loc}
        AND t.status = 'OK'
        AND to_tsvector(${cfg}::regconfig, t.title || ' ' || t.description)
            @@ plainto_tsquery(${cfg}::regconfig, ${q})
    )
    AND (
      d.source_language = ${loc}
      OR EXISTS (
        SELECT 1 FROM deal_translations t2
        WHERE t2.deal_id = d.id AND t2.locale = ${loc} AND t2.status = 'OK'
          AND t2.title <> '' AND t2.description <> ''
      )
    )`;
  }
  return sql`(d.title ILIKE ${'%' + q + '%'} OR d.description ILIKE ${'%' + q + '%'})`;
}