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');

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

    const adminDb = getAdminDb();
    
    // Get knowledge_items collection
    const knowledgeItemsRef = adminDb.collection('knowledge_items');
    const snapshot = await knowledgeItemsRef
      .where('projectId', '==', projectId)
      .limit(20)
      .get();
    
    const items = snapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data(),
    }));

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

