import { NextResponse } from 'next/server';
import { getAdminDb } from '@/lib/firebase/admin';

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const projectId = (url.searchParams.get('projectId') ?? '').trim();

    if (!projectId) {
      return NextResponse.json({ error: 'Missing projectId' }, { status: 400 });
    }

    const adminDb = getAdminDb();

    // Use a simple filter query without orderBy to avoid requiring a composite index.
    const snapshot = await adminDb
      .collection('knowledge_items')
      .where('projectId', '==', projectId)
      .get();

    const items = snapshot.docs.map((doc) => doc.data());

    return NextResponse.json({ count: items.length, items });
  } catch (error) {
    console.error('[debug/knowledge] Failed to list knowledge items', error);
    return NextResponse.json(
      {
        error: 'Failed to list knowledge items',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 },
    );
  }
}


