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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    
    // Authentication (skip in development if no auth header)
    const authHeader = request.headers.get('Authorization');
    const isDevelopment = process.env.NODE_ENV === 'development';
    
    if (!isDevelopment || authHeader?.startsWith('Bearer ')) {
      if (!authHeader?.startsWith('Bearer ')) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }

      const token = authHeader.substring(7);
      const auth = getAdminAuth();
      const decoded = await auth.verifyIdToken(token);
      
      if (!decoded?.uid) {
        return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
      }
    }

    // Fetch knowledge items from Firestore
    console.log('[API /knowledge/items] Fetching items for project:', projectId);
    
    let items = [];
    
    try {
      const adminDb = getAdminDb();
      const knowledgeSnapshot = await adminDb
        .collection('knowledge')
        .where('projectId', '==', projectId)
        .orderBy('createdAt', 'desc')
        .limit(100)
        .get();

      console.log('[API /knowledge/items] Found', knowledgeSnapshot.size, 'items');

      items = knowledgeSnapshot.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          title: data.title || data.content?.substring(0, 50) || 'Untitled',
          sourceType: data.sourceType,
          content: data.content,
          sourceMeta: data.sourceMeta,
          createdAt: data.createdAt?.toDate?.()?.toISOString() || data.createdAt,
          updatedAt: data.updatedAt?.toDate?.()?.toISOString() || data.updatedAt,
        };
      });
    } catch (firestoreError) {
      console.error('[API /knowledge/items] Firestore query failed:', firestoreError);
      console.error('[API /knowledge/items] This is likely due to missing Firebase Admin credentials or Firestore not being set up');
      // Return empty array instead of failing - the UI will show "No chats yet" and "No images yet"
      items = [];
    }

    return NextResponse.json({
      success: true,
      items,
      count: items.length,
    });
  } catch (error) {
    console.error('[API /knowledge/items] Error fetching knowledge items:', error);
    console.error('[API /knowledge/items] Error stack:', error instanceof Error ? error.stack : 'No stack trace');
    return NextResponse.json(
      { 
        error: 'Failed to fetch knowledge items',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

