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 limit = parseInt(searchParams.get('limit') || '10');

    console.log(`[API] Fetching sessions for project ${projectId}, limit ${limit}`);

    const adminDb = getAdminDb();
    let sessionsQuery = adminDb.collection('sessions');

    // Filter by projectId if provided
    if (projectId) {
      sessionsQuery = sessionsQuery.where('projectId', '==', projectId) as any;
    }

    const sessionsSnapshot = await sessionsQuery
      .orderBy('createdAt', 'desc')
      .limit(limit)
      .get();

    const sessions = sessionsSnapshot.docs.map(doc => {
      const data = doc.data();
      return {
        id: doc.id,
        session_id: doc.id,
        projectId: data.projectId,
        userId: data.userId,
        workspacePath: data.workspacePath,
        workspaceName: data.workspaceName,
        startTime: data.startTime,
        endTime: data.endTime,
        duration: data.duration,
        duration_minutes: data.duration ? Math.round(data.duration / 60) : 0,
        tokensUsed: data.tokensUsed || 0,
        total_tokens: data.tokensUsed || 0,
        cost: data.cost || 0,
        estimated_cost_usd: data.cost || 0,
        model: data.model || 'unknown',
        primary_ai_model: data.model || 'unknown',
        filesModified: data.filesModified || [],
        summary: data.conversationSummary || null,
        message_count: data.messageCount || 0,
        ide_name: 'Cursor',
        github_branch: data.githubBranch || null,
        conversation: data.conversation || [],
        file_changes: data.fileChanges || [],
        createdAt: data.createdAt,
        last_updated: data.updatedAt || data.createdAt,
      };
    });

    console.log(`[API] Found ${sessions.length} sessions from Firebase`);
    return NextResponse.json(sessions);
  } catch (error) {
    console.error('[API] Error fetching sessions:', error);
    return NextResponse.json([]);
  }
}
