/**
 * Shared RAG query utility for the Drafting Engine.
 *
 * Queries the bp-core-rag-service for relevant legal context.
 * Supports multi-collection search via POST /api/v1/search.
 * Used by both chat and draft routes.
 */

const RAG_SERVICE_URL = process.env.RAG_SERVICE_URL || 'http://bp-core-rag-service:8097'

/**
 * Query the RAG corpus for relevant legal documents.
 *
 * @param query - The search query (e.g. "Art. 35 DSGVO Risikobewertung")
 * @param topK - Number of results to return (default: 3)
 * @param collection - Optional RAG collection name (e.g. "bp_dsfa_corpus")
 * @returns Formatted string of legal context, or empty string on error
 */
export async function queryRAG(query: string, topK = 3, collection?: string): Promise<string> {
  try {
    const body: Record<string, unknown> = {
      query,
      top_k: topK,
    }
    if (collection) {
      body.collection = collection
    }

    const res = await fetch(`${RAG_SERVICE_URL}/api/v1/search`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(10000),
    })

    if (!res.ok) return ''

    const data = await res.json()
    if (data.results?.length > 0) {
      return data.results
        .map(
          (r: { source_name?: string; source_code?: string; content?: string }, i: number) =>
            `[Quelle ${i + 1}: ${r.source_name || r.source_code || 'Unbekannt'}]\n${r.content || ''}`
        )
        .join('\n\n---\n\n')
    }
    return ''
  } catch {
    return ''
  }
}
