export const dynamic = 'force-dynamic';
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const [totalVehicles, availableVehicles, soldVehicles, featuredVehicles, totalLeads, newLeads, contactedLeads, totalCategories, topViewed, recentLeads, leadsBySource, leadsByMonth] = await Promise.all([
      prisma.vehicle.count(),
      prisma.vehicle.count({ where: { status: 'AVAILABLE' } }),
      prisma.vehicle.count({ where: { status: 'SOLD' } }),
      prisma.vehicle.count({ where: { featured: true } }),
      prisma.lead.count(),
      prisma.lead.count({ where: { status: 'NEW' } }),
      prisma.lead.count({ where: { status: 'CONTACTED' } }),
      prisma.category.count(),
      prisma.vehicle.findMany({ orderBy: { viewCount: 'desc' }, take: 5, select: { id: true, title: true, viewCount: true, status: true } }),
      prisma.lead.findMany({ orderBy: { createdAt: 'desc' }, take: 5, include: { vehicle: { select: { title: true } } } }),
      prisma.lead.groupBy({ by: ['source'], _count: { id: true } }),
      prisma.$queryRaw`SELECT TO_CHAR("createdAt", 'YYYY-MM') as month, COUNT(*)::int as count FROM "Lead" WHERE "createdAt" >= NOW() - INTERVAL '6 months' GROUP BY month ORDER BY month ASC`,
    ]);

    return NextResponse.json({
      totalVehicles: totalVehicles ?? 0,
      availableVehicles: availableVehicles ?? 0,
      soldVehicles: soldVehicles ?? 0,
      featuredVehicles: featuredVehicles ?? 0,
      totalLeads: totalLeads ?? 0,
      newLeads: newLeads ?? 0,
      contactedLeads: contactedLeads ?? 0,
      totalCategories: totalCategories ?? 0,
      topViewed: topViewed ?? [],
      recentLeads: recentLeads ?? [],
      leadsBySource: leadsBySource ?? [],
      leadsByMonth: leadsByMonth ?? [],
    });
  } catch (error: any) {
    console.error('Stats error:', error);
    return NextResponse.json({ error: 'Failed to fetch stats' }, { status: 500 });
  }
}
