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

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

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

    const adminDb = getAdminDb();
    
    // Query sessions for this project
    let sessionsQuery = adminDb.collection('sessions');
    if (projectId) {
      sessionsQuery = sessionsQuery.where('projectId', '==', projectId) as any;
    }
    
    const sessionsSnapshot = await sessionsQuery.get();

    // Calculate stats
    let totalSessions = 0;
    let totalCost = 0;
    let totalTokens = 0;
    let totalDuration = 0;

    sessionsSnapshot.docs.forEach(doc => {
      const data = doc.data();
      totalSessions++;
      totalCost += data.cost || 0;
      totalTokens += data.tokensUsed || 0;
      totalDuration += data.duration || 0;
    });

    // Query work completed for this project
    let workQuery = adminDb.collection('workCompleted');
    if (projectId) {
      workQuery = workQuery.where('projectId', '==', projectId) as any;
    }
    
    const workSnapshot = await workQuery.get();
    const workCompleted = workSnapshot.size;

    const stats: DashboardStats = {
      totalSessions,
      totalCost,
      totalTokens,
      totalFeatures: workCompleted,
      completedFeatures: workCompleted,
      totalDuration: Math.round(totalDuration / 60), // Convert to minutes
    };

    console.log(`[API] Stats fetched successfully:`, stats);
    return NextResponse.json(stats);
  } catch (error) {
    console.error('[API] Error fetching stats:', error);
    
    const emptyStats: DashboardStats = {
      totalSessions: 0,
      totalCost: 0,
      totalTokens: 0,
      totalFeatures: 0,
      completedFeatures: 0,
      totalDuration: 0,
    };
    
    return NextResponse.json(emptyStats);
  }
}
