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());

    // Find date range
    const dates = conversations
      .filter(c => c.createdAt)
      .map(c => new Date(c.createdAt))
      .sort((a, b) => a.getTime() - b.getTime());

    if (dates.length === 0) {
      return NextResponse.json({ error: 'No conversations with dates found' });
    }

    const earliest = dates[0];
    const latest = dates[dates.length - 1];
    const span = Math.floor((latest.getTime() - earliest.getTime()) / (1000 * 60 * 60 * 24));

    // Find the actual conversation names for earliest and latest
    const earliestConv = conversations.find(c => 
      new Date(c.createdAt).getTime() === earliest.getTime()
    );
    const latestConv = conversations.find(c => 
      new Date(c.createdAt).getTime() === latest.getTime()
    );

    return NextResponse.json({
      totalConversations: conversations.length,
      dateRange: {
        earliest: earliest.toISOString(),
        latest: latest.toISOString(),
        spanDays: span
      },
      oldestConversation: {
        name: earliestConv?.name || 'Unknown',
        date: earliest.toISOString()
      },
      newestConversation: {
        name: latestConv?.name || 'Unknown',
        date: latest.toISOString()
      }
    });

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


