import { NextResponse } from 'next/server';
import { getAdminAuth } from '@/lib/firebase/admin';
import { getAlloyDbClient } from '@/lib/db/alloydb';

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 chunks from AlloyDB
    let chunks = [];
    let count = 0;
    
    try {
      const pool = await getAlloyDbClient();
      const result = await pool.query(
        `SELECT 
          id, 
          chunk_index,
          content, 
          source_type, 
          importance,
          created_at
        FROM knowledge_chunks 
        WHERE project_id = $1 
        ORDER BY created_at DESC
        LIMIT 100`,
        [projectId]
      );
      
      chunks = result.rows;
      count = result.rowCount || 0;
      console.log('[API /knowledge/chunks] Found', count, 'chunks');
    } catch (dbError) {
      console.error('[API /knowledge/chunks] AlloyDB query failed:', dbError);
      console.error('[API /knowledge/chunks] This is likely due to AlloyDB not being configured or connected');
      // Return empty array instead of failing
      chunks = [];
      count = 0;
    }

    return NextResponse.json({
      success: true,
      chunks,
      count,
    });
  } catch (error) {
    console.error('[API] Error fetching knowledge chunks:', error);
    return NextResponse.json(
      { error: 'Failed to fetch knowledge chunks' },
      { status: 500 }
    );
  }
}

