import type { Knex } from 'knex';

/** Escape LIKE wildcards in user input (values are still parameter-bound by Knex). */
export const likeEscape = (s: string) => s.replace(/[\\%_]/g, (c) => `\\${c}`);

/** MySQL/MariaDB boolean-mode prefix query: "napa ext" → "+napa* +ext*" (operators stripped). */
export function ftBoolean(q: string) {
  const words = q
    .toLowerCase()
    .replace(/[^\p{L}\p{N}\s]/gu, ' ')
    .split(/\s+/)
    .filter((w) => w.length >= 2);
  return words.map((w) => `+${w}*`).join(' ');
}

/**
 * Name search: prefix LIKE (uses the name index, works for 2-letter queries and short names like "Ace")
 * OR FULLTEXT boolean prefix match for longer, multi-word queries.
 */
export function whereNameMatches(qb: Knex.QueryBuilder, column: string, q: string) {
  const term = q.trim();
  const ft = ftBoolean(term);
  qb.where((w) => {
    w.where(column, 'like', `${likeEscape(term)}%`).orWhere(column, 'like', `% ${likeEscape(term)}%`);
    if (term.length >= 3 && ft) w.orWhereRaw(`MATCH(${column}) AGAINST (? IN BOOLEAN MODE)`, [ft]);
  });
}

/**
 * Rank exact match first, then word-prefix ("Fexo Plus"), then prefix ("Fexomin"), then other matches.
 */
export const prefixRank = (column: string, q: string) => {
  const raw = q.trim();
  const esc = likeEscape(raw);
  return [
    `CASE WHEN LOWER(${column}) = LOWER(?) THEN 0 WHEN ${column} LIKE ? THEN 1 WHEN ${column} LIKE ? THEN 2 ELSE 3 END`,
    [raw, `${esc} %`, `${esc}%`],
  ] as const;
};

/**
 * Typo / extra-letter fallback candidates for queries that return 0 direct hits:
 * e.g. "napaaaaxs" → ["napaxs", "napax", "napa", "nap"], "fexooos" → ["fexos", "fexo", "fex"].
 */
export function fallbackTerms(q: string): string[] {
  const clean = q
    .trim()
    .toLowerCase()
    .replace(/[^\p{L}\p{N}\s]/gu, ' ')
    .replace(/\s+/g, ' ')
    .trim();
  if (clean.length < 3) return [];

  const firstWord = clean.split(' ')[0];
  const deduped = firstWord.replace(/(.)\1+/gu, '$1');
  const out: string[] = [];
  const seen = new Set<string>([clean]);

  const push = (s: string) => {
    if (s.length >= 3 && !seen.has(s)) {
      seen.add(s);
      out.push(s);
    }
  };

  // 1. Collapsed repeated letters ("fexooos" -> "fexos", "napaaaaxs" -> "napaxs")
  push(deduped);

  // 2. Progressively trim trailing characters from deduped & original (down to 3 chars)
  const sources = deduped !== firstWord ? [deduped, firstWord] : [firstWord];
  for (const src of sources) {
    const start = Math.min(src.length - 1, 14);
    for (let len = start; len >= 3; len--) {
      push(src.slice(0, len));
    }
  }
  return out;
}

export const toNum = (v: unknown) => (v === null || v === undefined ? null : Number(v));
export const count = async (qb: Knex.QueryBuilder) => {
  const row = (await qb.clone().clearSelect().clearOrder().count({ n: '*' }).first()) as
    { n: number | string } | undefined;
  return Number(row?.n ?? 0);
};
