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

    const conversations = conversationsSnapshot.docs.map(doc => doc.data());

    // Group by workspace path
    const workspaceGroups: Record<string, number> = {};
    const githubGroups: Record<string, number> = {};

    conversations.forEach(conv => {
      const workspace = conv.workspacePath || 'unknown';
      const github = conv.githubUrl || 'none';
      
      workspaceGroups[workspace] = (workspaceGroups[workspace] || 0) + 1;
      githubGroups[github] = (githubGroups[github] || 0) + 1;
    });

    // Sort by count
    const workspaceList = Object.entries(workspaceGroups)
      .map(([path, count]) => ({ path, count }))
      .sort((a, b) => b.count - a.count);

    const githubList = Object.entries(githubGroups)
      .map(([url, count]) => ({ url, count }))
      .sort((a, b) => b.count - a.count);

    return NextResponse.json({
      totalConversations: conversations.length,
      uniqueWorkspaces: workspaceList.length,
      uniqueRepos: githubList.length,
      workspaces: workspaceList,
      repos: githubList
    });

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


