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 cursor conversations for this project
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .orderBy('createdAt', 'desc')
      .get();

    const conversations = conversationsSnapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data()
    }));

    // Get the messages data
    const messagesDoc = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorData')
      .doc('messages')
      .get();

    const messagesData = messagesDoc.exists ? messagesDoc.data() : null;

    return NextResponse.json({
      projectId,
      conversationCount: conversations.length,
      conversations,
      messagesData: messagesData ? {
        promptCount: messagesData.prompts?.length || 0,
        generationCount: messagesData.generations?.length || 0,
        importedAt: messagesData.importedAt
      } : null
    });

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


