/**
 * RAG Query API
 * 
 * Allows agents and the dashboard to query the RAG system
 * for grounded business context.
 * 
 * POST /api/gfs/rag/query
 * Body: { query: string, category?: string, maxChunks?: number }
 */

import { NextRequest, NextResponse } from 'next/server';
import { retrieveContext } from '@/lib/gfs/rag';
import type { RAGDocumentCategory } from '@/lib/gfs/rag';

export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { query, category, maxChunks } = body;

    if (!query || typeof query !== 'string') {
      return NextResponse.json(
        { error: 'query is required and must be a string' },
        { status: 400 }
      );
    }

    const context = retrieveContext(query, {
      maxChunks: maxChunks || 5,
      boostCategories: category
        ? [category as RAGDocumentCategory]
        : undefined,
    });

    return NextResponse.json({
      success: true,
      context,
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: 'RAG query failed',
        details: error instanceof Error ? error.message : 'Unknown',
      },
      { status: 500 }
    );
  }
}
