import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase/admin';

export async function GET(request: NextRequest) {
  try {
    const projectId = request.nextUrl.searchParams.get('projectId');
    
    if (!projectId) {
      return NextResponse.json({ error: 'Missing projectId' }, { status: 400 });
    }

    // Get all unknown conversations grouped by session
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .where('sessionProject', '==', 'unknown')
      .get();

    const sessionMap: Record<number, any[]> = {};
    
    conversationsSnapshot.docs.forEach(doc => {
      const data = doc.data();
      const sessionId = data.sessionId;
      
      if (!sessionMap[sessionId]) {
        sessionMap[sessionId] = [];
      }
      
      sessionMap[sessionId].push({
        name: data.name,
        date: data.sessionDate,
        createdAt: data.createdAt
      });
    });

    // Convert to array and take sample
    const sessions = Object.entries(sessionMap).map(([sessionId, conversations]) => ({
      sessionId: parseInt(sessionId),
      date: conversations[0].date,
      conversationCount: conversations.length,
      conversationNames: conversations.map(c => c.name)
    }));

    return NextResponse.json({
      totalUnknownSessions: sessions.length,
      totalUnknownConversations: conversationsSnapshot.size,
      sample: sessions.slice(0, 30)
    });

  } catch (error) {
    console.error('Error fetching unknown sessions:', error);
    return NextResponse.json(
      { error: 'Failed to fetch', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

