/**
 * Document Search
 * Full-text search and document discovery
 */

import { query } from './client';
import { listDocuments, getDocumentById } from './schema';

export interface DocumentSearchResult {
  documents: Array<{
    id: string;
    title: string;
    type: string;
    content?: string;
    file_url?: string;
    created_at: Date;
    relevance_score?: number;
  }>;
  total: number;
  page: number;
  page_size: number;
}

export interface SearchFilters {
  type?: string;
  matter_id?: string;
  created_after?: Date;
  created_before?: Date;
  search?: string;
}

/**
 * Search documents
 */
export async function searchDocuments(
  filters: SearchFilters = {},
  page = 1,
  page_size = 50
): Promise<DocumentSearchResult> {
  const conditions: string[] = [];
  const params: unknown[] = [];
  let paramIndex = 1;

  if (filters.type) {
    conditions.push(`type = $${paramIndex++}`);
    params.push(filters.type);
  }

  if (filters.created_after) {
    conditions.push(`created_at >= $${paramIndex++}`);
    params.push(filters.created_after);
  }

  if (filters.created_before) {
    conditions.push(`created_at <= $${paramIndex++}`);
    params.push(filters.created_before);
  }

  if (filters.search) {
    conditions.push(
      `(title ILIKE $${paramIndex} OR content ILIKE $${paramIndex} OR ocr_text ILIKE $${paramIndex})`
    );
    params.push(`%${filters.search}%`);
    paramIndex++;
  }

  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

  // Get total count
  const countResult = await query<{ count: string }>(
    `SELECT COUNT(*) as count FROM documents ${whereClause}`,
    params
  );
  const total = parseInt(countResult.rows[0]?.count || '0', 10);

  // Get paginated results
  const offset = (page - 1) * page_size;
  const result = await query<{
    id: string;
    title: string;
    type: string;
    content?: string;
    file_url?: string;
    created_at: Date;
  }>(
    `SELECT id, title, type, content, file_url, created_at 
     FROM documents 
     ${whereClause}
     ORDER BY created_at DESC 
     LIMIT $${paramIndex++} OFFSET $${paramIndex++}`,
    [...params, page_size, offset]
  );

  return {
    documents: result.rows,
    total,
    page,
    page_size,
  };
}

/**
 * Get search suggestions
 */
export async function getSearchSuggestions(query: string, limit = 10): Promise<string[]> {
  if (!query || query.length < 2) {
    return [];
  }

  const result = await query<{ title: string }>(
    `SELECT DISTINCT title 
     FROM documents 
     WHERE title ILIKE $1 
     ORDER BY title 
     LIMIT $2`,
    [`%${query}%`, limit]
  );

  return result.rows.map((row) => row.title);
}

