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');
    const minScore = parseInt(request.nextUrl.searchParams.get('minScore') || '0');
    
    if (!projectId) {
      return NextResponse.json({ error: 'Missing projectId' }, { status: 400 });
    }

    // Get all conversations
    const conversationsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('cursorConversations')
      .get();

    const conversations = conversationsSnapshot.docs
      .map(doc => {
        const data = doc.data();
        return {
          name: data.name,
          relevanceScore: data.relevanceScore || 0,
          createdAt: data.createdAt,
          workspacePath: data.workspacePath
        };
      })
      .filter(c => c.relevanceScore >= minScore)
      .sort((a, b) => b.relevanceScore - a.relevanceScore);

    // Group by score
    const scoreGroups: Record<number, number> = {};
    conversationsSnapshot.docs.forEach(doc => {
      const score = doc.data().relevanceScore || 0;
      scoreGroups[score] = (scoreGroups[score] || 0) + 1;
    });

    return NextResponse.json({
      totalConversations: conversationsSnapshot.size,
      filteredConversations: conversations.length,
      minScore,
      scoreDistribution: scoreGroups,
      conversations: conversations.slice(0, 50) // First 50
    });

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

