/**
 * PostgreSQL tsvector full-text search across entities, content, and annotations.
 */

import { query } from "../../db.js";

export interface FtsResult {
  source: string;
  ref_id: string;
  text: string | null;
  rank: number;
}

/**
 * Full-text search using tsvector GIN indexes.
 * Builds a simple AND tsquery from whitespace-separated words.
 */
export async function ftsSearch(
  q: string,
  limit = 20,
): Promise<FtsResult[]> {
  const tsq = q
    .trim()
    .split(/\s+/)
    .join(" & ");

  const { rows } = await query<FtsResult>(
    `
    SELECT 'entity' AS source, id AS ref_id, name AS text,
           ts_rank(fts, to_tsquery('simple', $1)) AS rank
    FROM entities
    WHERE fts @@ to_tsquery('simple', $1)
    UNION ALL
    SELECT 'content', id, LEFT(text, 200),
           ts_rank(fts, to_tsquery('simple', $1))
    FROM content
    WHERE fts @@ to_tsquery('simple', $1)
    UNION ALL
    SELECT 'annotation', id::text, LEFT(note, 200),
           ts_rank(fts, to_tsquery('simple', $1))
    FROM annotations
    WHERE fts @@ to_tsquery('simple', $1)
    ORDER BY rank DESC
    LIMIT $2
    `,
    [tsq, limit],
  );

  return rows;
}
