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 5 random conversations with content
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .limit(5)
      .get();

    const samples = conversationsSnapshot.docs.map(doc => {
      const data = doc.data();
      return {
        name: data.name,
        messageCount: data.messageCount || 0,
        promptCount: data.prompts?.length || 0,
        generationCount: data.generations?.length || 0,
        filesCount: data.files?.length || 0,
        sampleFiles: (data.files || []).slice(0, 3),
        samplePrompt: data.prompts?.[0]?.text?.substring(0, 100) || 'none',
        hasContent: !!(data.prompts?.length || data.generations?.length)
      };
    });

    // Get overall stats
    const allConversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .get();

    let totalWithContent = 0;
    let totalWithFiles = 0;
    let totalMessages = 0;

    allConversationsSnapshot.docs.forEach(doc => {
      const data = doc.data();
      if (data.prompts?.length || data.generations?.length) {
        totalWithContent++;
      }
      if (data.files?.length) {
        totalWithFiles++;
      }
      totalMessages += data.messageCount || 0;
    });

    return NextResponse.json({
      totalConversations: allConversationsSnapshot.size,
      totalWithContent,
      totalWithFiles,
      totalMessages,
      samples
    });

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

