// app/api/mines/projects/[id]/chunks/route.js
//
// GET — RAG retrieval endpoint (agent + debug use). [id] is the mines_projects.id.
//   ?query=<text>&category=<document_category>&limit=10
// Returns top-K document chunks by similarity (vector when embeddings exist,
// text search otherwise). Authenticated — document text is project-private.

import { NextResponse } from 'next/server';
import { requireFreshMembership, requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { retrieveChunks } from '@/lib/mines/rag.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(request, { params }) {
  const { id } = await params;

  try {
    const session = await requireSession(request);
    await requireFreshMembership(session, session.org_id);
    requireRole(session, 'viewer', session.org_id);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return NextResponse.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  const { searchParams } = new URL(request.url);
  const query = (searchParams.get('query') || '').trim();
  const category = searchParams.get('category') || null;
  const limit = Math.max(1, Math.min(50, Number(searchParams.get('limit')) || 10));

  if (!query) {
    return NextResponse.json({ error: 'query parameter is required' }, { status: 400 });
  }

  try {
    const result = await retrieveChunks(id, query, limit, category);
    return NextResponse.json({ data: result.chunks, mode: result.mode, count: result.chunks.length });
  } catch (err) {
    console.error('GET /api/mines/projects/[id]/chunks error:', err);
    return NextResponse.json({ error: 'Retrieval failed' }, { status: 500 });
  }
}
