import { NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireAdmin } from '@/lib/auth';

export async function GET() {
  const unauthorized = await requireAdmin();
  if (unauthorized) return unauthorized;

  const [sessions] = await query<{ count: string }>('SELECT COUNT(*) as count FROM sessions');
  const [paid] = await query<{ count: string }>('SELECT COUNT(*) as count FROM sessions WHERE is_paid = TRUE');
  const [leads] = await query<{ count: string }>('SELECT COUNT(*) as count FROM leads');
  const [tokens] = await query<{ total: string }>('SELECT COALESCE(SUM(tokens_used), 0) as total FROM usage');

  const toolBreakdown = await query<{ tool: string; count: string }>(
    'SELECT tool, COUNT(*) as count FROM sessions GROUP BY tool ORDER BY count DESC'
  );

  return NextResponse.json({
    total_sessions: parseInt(sessions.count),
    paid_sessions: parseInt(paid.count),
    total_leads: parseInt(leads.count),
    total_tokens: parseInt(tokens.total),
    by_tool: toolBreakdown,
  });
}
