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

export async function GET(
  request: Request,
  context: { params: Promise<{ projectId: string }> | { projectId: string } }
) {
  try {
    const params = 'then' in context.params ? await context.params : context.params;
    const projectId = params.projectId;

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

    const adminDb = getAdminDb();

    // Get ALL knowledge items for this project
    const knowledgeSnapshot = await adminDb
      .collection('knowledge_items')
      .where('projectId', '==', projectId)
      .get();

    const items = knowledgeSnapshot.docs.map(doc => {
      const data = doc.data();
      return {
        id: doc.id,
        title: data.title,
        sourceType: data.sourceType,
        contentLength: data.content?.length || 0,
        createdAt: data.createdAt,
        tags: data.sourceMeta?.tags || [],
      };
    });

    // Get project info
    const projectDoc = await adminDb.collection('projects').doc(projectId).get();
    const projectData = projectDoc.data();

    return NextResponse.json({
      projectId,
      projectName: projectData?.name,
      currentPhase: projectData?.currentPhase,
      totalKnowledgeItems: items.length,
      items,
      extractionHandoff: projectData?.phaseData?.phaseHandoffs?.extraction,
    });
  } catch (error) {
    console.error('[debug-knowledge] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to debug knowledge',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

