import { NextResponse } from 'next/server';
import { getAdminDb } from '@/lib/firebase/admin';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get('projectId');
    const userId = searchParams.get('userId');

    const adminDb = getAdminDb();
    
    // Get all sessions for this user
    const sessionsSnapshot = await adminDb
      .collection('sessions')
      .where('userId', '==', userId)
      .get();

    const allSessions = sessionsSnapshot.docs.map(doc => {
      const data = doc.data();
      return {
        id: doc.id,
        projectId: data.projectId || null,
        workspacePath: data.workspacePath || null,
        workspaceName: data.workspaceName || null,
        needsProjectAssociation: data.needsProjectAssociation,
        messageCount: data.messageCount,
        conversationLength: data.conversation?.length || 0,
      };
    });

    // Filter sessions that match this project
    const matchingSessions = allSessions.filter(s => s.projectId === projectId);

    return NextResponse.json({
      totalSessions: allSessions.length,
      matchingSessions: matchingSessions.length,
      allSessions,
      projectId,
      userId,
    });
  } catch (error: any) {
    console.error('[Admin Check Sessions] Error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

